I found an issue with the built-in API for retrieving addresses from coordinates. The API only works with the specific coordinates already written in the URL. For example, the URL for reverse geocoding is:
https://maps.googleapis.com/maps/api/geocode/json?latlng=54.21306002635472,-2.2815815580049694&key=YOUR_API_KEY
.
The passed coordinates don't seem to work.
Link to tutorial: https://youtu.be/oz8POsAyXJA
Below is the code for custom action:
// Automatic FlutterFlow imports
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<dynamic>> reverseGeocodingAPI(
String latitude,
String longitude,
String apiKey,
) async {
String baseUrl = "https://maps.googleapis.com/maps/api/geocode/json";
String url = "$baseUrl?latlng=$latitude,$longitude&key=$apiKey";
// Making the API call
final response = await http.get(Uri.parse(url));
// Checking if the response status is 200 (OK)
if (response.statusCode == 200) {
print('Reverse geocoding successfully performed');
final Map<String, dynamic> jsonResponse = json.decode(response.body);
final List<dynamic> results = jsonResponse['results'];
// Checking if there are any results
if (results.isEmpty) {
return [
{'formatted_address': 'No places found'}
];
} else {
// Return all details of the results
return results;
}
} else {
print('Error performing reverse geocoding: ${response.statusCode}');
print('Response body: ${response.body}');
return [
{'formatted_address': 'Error'}
];
}
}
You can retrieve the address using Json address. Below are some to get you started.
$.formatted_address
$.address_components[?(@.types[0] == "postal_code")].long_name
$.address_components[?(@.types[0] =="administrative_area_level_1")].long_name
$.address_components[?(@.types[0] =="locality")].long_name