Skip to content

Instantly share code, notes, and snippets.

@iamEtornam
Created March 27, 2023 18:55
Show Gist options
  • Save iamEtornam/f1b8ef7d55da80504fb627feca6b8471 to your computer and use it in GitHub Desktop.
Save iamEtornam/f1b8ef7d55da80504fb627feca6b8471 to your computer and use it in GitHub Desktop.
Location address conversion algorithm in dart
///In this implementation, the algorithm divides the map into a grid of 0.05 degrees in width and height, which provides a ///balance between granularity and uniqueness of the address identifier. The algorithm uses a reverse geocoding API to ///retrieve the administrative area, city, and street names for the given location, and includes these components in the ///address identifier along with the grid coordinates. The format of the address identifier is designed to be human-readable ///and consistent with local addressing conventions.
String getAddressFromLocation(double latitude, double longitude) {
// Define the size of the grid in degrees
final double gridWidth = 0.05;
final double gridHeight = 0.05;
// Calculate the grid coordinates for the given latitude and longitude
final int x = ((longitude + 180) / gridWidth).floor();
final int y = ((latitude + 90) / gridHeight).floor();
// Retrieve the administrative area, city, and street names for the given location using a reverse geocoding API
final String adminArea = await reverseGeocode(latitude, longitude, GeocodeLevel.AdminArea);
final String city = await reverseGeocode(latitude, longitude, GeocodeLevel.Locality);
final String street = await reverseGeocode(latitude, longitude, GeocodeLevel.Thoroughfare);
// Create the address identifier using a format that includes the administrative area, city, street, and grid coordinates
final String address = '${adminArea}_${city}_${street}_${x}_${y}';
return address;
}
enum GeocodeLevel {
Country,
AdminArea,
Locality,
Thoroughfare
}
Future<String> reverseGeocode(double latitude, double longitude, GeocodeLevel level) async {
// Use a reverse geocoding API to retrieve the address components for the given latitude and longitude
final String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=$latitude,$longitude&result_type=$level&key=YOUR_API_KEY';
final http.Response response = await http.get(Uri.parse(url));
final Map<String, dynamic> data = jsonDecode(response.body);
// Parse the address components and return the requested component (e.g. administrative area, city, or street name)
final List<dynamic> results = data['results'];
if (results.isNotEmpty) {
final List<dynamic> addressComponents = results[0]['address_components'];
final String component = level == GeocodeLevel.Thoroughfare ? 'route' : level.toString().split('.')[1];
for (final componentData in addressComponents) {
if (componentData['types'].contains(component)) {
return componentData['long_name'];
}
}
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment