I'm trying to access the Google Maps Geocoding JavaScript API from Dart.
I have this code, which uses the js package to translate to Dart:
@JS('google.maps')
library google_maps;
import 'package:js/js.dart';
@JS()
class Geocoder {
external Geocoder();
external geocode(GeocodeOptions options, void Function(List<GeocodeResult> results, String status) callback);
}
@JS()
@anonymous
class GeocodeResult {
// ...
}
... And I'm calling it from my application like this:
geocoder.geocode(
GeocodeOptions(
address: address,
region: region,
),
allowInterop((results, status) {
// ???
}),
);
The problem is with the type of the results
list in the callback function:
void Function(List<GeocodeResult> results, String status)
With the type set to GeocodeResult
, I get an error:
Expected a value of type
List<GeocodeResult>
but got one of typeList<dynamic>
But if I change the type to dynamic
, then my callback function in dart receives a List<NativeJavaScriptObject>
.
I don't know what to do with a NativeJavascriptObject
!
Map
, so I can't use square brackets — result['geometry']
List.cast<GeocodeResult>()
then I get an error: dart.notNull() is not a Functionresult.geometry
Any and all suggestions welcome, thank you.
Okay, I've got it working by converting to JSON in JavaScript and then parsing the JSON into a Map
in dart:
geocoder.geocode(
GeocodeOptions(
address: address,
region: region,
),
allowInterop((results, status) {
final list = List<Map<String, dynamic>>();
results.forEach((jsObject) {
//Convert NativeJavascriptObject to Map by encoding and decoding JSON
final json = stringify(jsObject);
final map = Map<String, dynamic>.from(jsonDecode(json));
list.add(map);
});
}),
);
This uses stringify()
, below, which calls JSON.stringify()
from JavaScript.
@JS('JSON.stringify')
external String stringify(Object obj);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.