Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added web support #72

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,9 @@ android {
defaultConfig {
minSdkVersion 16
}

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
168 changes: 77 additions & 91 deletions android/src/main/java/com/aloisdeniel/geocoder/GeocoderPlugin.java
Original file line number Diff line number Diff line change
@@ -1,49 +1,47 @@
package com.aloisdeniel.geocoder;

import androidx.annotation.NonNull;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Collections;
import java.util.HashMap;
import java.io.IOException;
import java.lang.Exception;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/**
* NotAvailableException
*/
class NotAvailableException extends Exception {
NotAvailableException() {}
}

/**
* GeocoderPlugin
*/
public class GeocoderPlugin implements MethodCallHandler {
public class GeocoderPlugin implements FlutterPlugin, MethodCallHandler {

private Geocoder geocoder;
private MethodChannel channel;

public GeocoderPlugin(Context context) {

this.geocoder = new Geocoder(context);
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
channel = new MethodChannel(binding.getBinaryMessenger(), "github.com/aloisdeniel/geocoder");
channel.setMethodCallHandler(this);
geocoder = new Geocoder(binding.getApplicationContext());
}

/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "github.com/aloisdeniel/geocoder");
channel.setMethodCallHandler(new GeocoderPlugin(registrar.context()));
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);

}

// MethodChannel.Result wrapper that responds on the platform thread.
Expand All @@ -58,36 +56,18 @@ private static class MethodResultWrapper implements Result {

@Override
public void success(final Object result) {
handler.post(
new Runnable() {
@Override
public void run() {
methodResult.success(result);
}
});
handler.post(() -> methodResult.success(result));
}

@Override
public void error(
final String errorCode, final String errorMessage, final Object errorDetails) {
handler.post(
new Runnable() {
@Override
public void run() {
methodResult.error(errorCode, errorMessage, errorDetails);
}
});
handler.post(() -> methodResult.error(errorCode, errorMessage, errorDetails));
}

@Override
public void notImplemented() {
handler.post(
new Runnable() {
@Override
public void run() {
methodResult.notImplemented();
}
});
methodResult.notImplemented();
}
}

Expand All @@ -98,11 +78,10 @@ public void onMethodCall(MethodCall call, Result rawResult) {
if (call.method.equals("findAddressesFromQuery")) {
String address = (String) call.argument("address");
findAddressesFromQuery(address, result);
}
else if (call.method.equals("findAddressesFromCoordinates")) {
} else if (call.method.equals("findAddressesFromCoordinates")) {
float latitude = ((Number) call.argument("latitude")).floatValue();
float longitude = ((Number) call.argument("longitude")).floatValue();
findAddressesFromCoordinates(latitude,longitude, result);
findAddressesFromCoordinates(latitude, longitude, result);
} else {
result.notImplemented();
}
Expand All @@ -115,68 +94,68 @@ private void assertPresent() throws NotAvailableException {
}

private void findAddressesFromQuery(final String address, final Result result) {

final GeocoderPlugin plugin = this;
new AsyncTask<Void, Void, List<Address>>() {
@Override
protected List<Address> doInBackground(Void... params) {
try {
plugin.assertPresent();
return geocoder.getFromLocationName(address, 20);
} catch (IOException ex) {
return null;
} catch (NotAvailableException ex) {
return new ArrayList<>();
}
@Override
protected List<Address> doInBackground(Void... params) {
try {
plugin.assertPresent();
return geocoder.getFromLocationName(address, 20);
} catch (IOException ex) {
return null;
} catch (NotAvailableException ex) {
return new ArrayList<>();
}
}

@Override
protected void onPostExecute(List<Address> addresses) {
if (addresses != null) {
if (addresses.isEmpty())
result.error("not_available", "Empty", null);
@Override
protected void onPostExecute(List<Address> addresses) {
if (addresses != null) {
if (addresses.isEmpty())
result.error("not_available", "Empty", null);

else result.success(createAddressMapList(addresses));
}
else result.error("failed", "Failed", null);
}
else
result.success(createAddressMapList(addresses));
} else
result.error("failed", "Failed", null);
}
}.execute();
}

private void findAddressesFromCoordinates(final float latitude, final float longitude, final Result result) {
final GeocoderPlugin plugin = this;
new AsyncTask<Void, Void, List<Address>>() {
@Override
protected List<Address> doInBackground(Void... params) {
try {
plugin.assertPresent();
return geocoder.getFromLocation(latitude, longitude, 20);
} catch (IOException ex) {
return null;
} catch (NotAvailableException ex) {
return new ArrayList<>();
}
@Override
protected List<Address> doInBackground(Void... params) {
try {
plugin.assertPresent();
return geocoder.getFromLocation(latitude, longitude, 20);
} catch (IOException ex) {
return null;
} catch (NotAvailableException ex) {
return new ArrayList<>();
}
}

@Override
protected void onPostExecute(List<Address> addresses) {
if (addresses != null) {
if (addresses.isEmpty())
result.error("not_available", "Empty", null);

else result.success(createAddressMapList(addresses));
}
else result.error("failed", "Failed", null);
}
@Override
protected void onPostExecute(List<Address> addresses) {
if (addresses != null) {
if (addresses.isEmpty())
result.error("not_available", "Empty", null);
else
result.success(createAddressMapList(addresses));
} else
result.error("failed", "Failed", null);
}
}.execute();
}

private Map<String, Object> createCoordinatesMap(Address address) {

if(address == null)
return null;
if (address == null)
return Collections.emptyMap();

Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<>();

result.put("latitude", address.getLatitude());
result.put("longitude", address.getLongitude());
Expand All @@ -186,8 +165,8 @@ private Map<String, Object> createCoordinatesMap(Address address) {

private Map<String, Object> createAddressMap(Address address) {

if(address == null)
return null;
if (address == null)
return Collections.emptyMap();

// Creating formatted address
StringBuilder sb = new StringBuilder();
Expand All @@ -198,7 +177,7 @@ private Map<String, Object> createAddressMap(Address address) {
sb.append(address.getAddressLine(i));
}

Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<>();

result.put("coordinates", createCoordinatesMap(address));
result.put("featureName", address.getFeatureName());
Expand All @@ -218,10 +197,10 @@ private Map<String, Object> createAddressMap(Address address) {

private List<Map<String, Object>> createAddressMapList(List<Address> addresses) {

if(addresses == null)
return new ArrayList<Map<String, Object>>();
if (addresses == null)
return new ArrayList<>();

List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(addresses.size());
List<Map<String, Object>> result = new ArrayList<>(addresses.size());

for (Address address : addresses) {
result.add(createAddressMap(address));
Expand All @@ -231,3 +210,10 @@ private List<Map<String, Object>> createAddressMapList(List<Address> addresses)
}
}

/**
* NotAvailableException
*/
class NotAvailableException extends Exception {
NotAvailableException() {
}
}
13 changes: 3 additions & 10 deletions lib/geocoder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,7 @@ export 'model.dart';

class Geocoder {
static final Geocoding local = LocalGeocoding();
static Geocoding google(
String apiKey, {
String? language,
Map<String, Object>? headers,
bool preserveHeaderCase = false,
}) =>
GoogleGeocoding(apiKey,
language: language,
headers: headers,
preserveHeaderCase: preserveHeaderCase);
static Geocoding google(String apiKey,
{String? language, Map<String, String>? headers}) =>
GoogleGeocoding(apiKey, language: language, headers: headers);
}
24 changes: 6 additions & 18 deletions lib/services/distant_google.dart
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'dart:io';

import 'package:geocoder/model.dart';
import 'package:geocoder/services/base.dart';
import 'package:http/http.dart' as http;

/// Geocoding and reverse geocoding through requests to Google APIs.
class GoogleGeocoding implements Geocoding {
static const _host = 'https://maps.google.com/maps/api/geocode/json';

final String apiKey;
final String? language;
final Map<String, Object>? headers;
final bool preserveHeaderCase;

final HttpClient _httpClient;
final Map<String, String>? headers;

GoogleGeocoding(
this.apiKey, {
this.language,
this.headers,
this.preserveHeaderCase = false,
}) : _httpClient = HttpClient();
});

Future<List<Address>> findAddressesFromCoordinates(
Coordinates coordinates) async {
Expand All @@ -40,19 +36,11 @@ class GoogleGeocoding implements Geocoding {
Future<List<Address>?> _send(String url) async {
//print("Sending $url...");
final uri = Uri.parse(url);
final request = await this._httpClient.getUrl(uri);
if (headers != null) {
headers!.forEach((key, value) {
request.headers.add(key, value, preserveHeaderCase: preserveHeaderCase);
});
}
final response = await request.close();
final responseBody = await utf8.decoder.bind(response).join();
//print("Received $responseBody...");
var data = jsonDecode(responseBody);
final response = await http.get(uri, headers: headers);

var results = data["results"];
var data = jsonDecode(response.body);

var results = data["results"];
if (results == null) return null;

return results
Expand Down
3 changes: 2 additions & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ version: 0.3.0
homepage: https://github.com/aloisdeniel/flutter_geocoder

environment:
sdk: ">=2.12.0 <3.0.0"
sdk: '>=2.12.0 <3.0.0'

dependencies:
flutter:
sdk: flutter
http: ^0.13.4

flutter:
plugin:
Expand Down