1

I have just developed an app using dart and flutter which I can obtain latitude and longitude of the location. My app can handle this. But I want to convert this longitude and latitude to open location codes(plus code) and show corresponding plus code in my app view

Also if I enter plus code also for the second stage it will convert to longitude and latitude.

I am stuck with this conversion.

If anyone here help me I will really be appreciated.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • I found a [related question](https://stackoverflow.com/questions/54761683/get-full-address-details-based-on-current-locations-latitude-and-longitude-in-f) on Stackoverflow – Pascal Gehring Dec 20 '20 at 10:27
  • Have a look at this: https://github.com/google/open-location-code/blob/master/dart/lib/src/open_location_code.dart – Constantin Dec 23 '20 at 14:06
  • This has detailed info on the simple conversion formula: https://www.dcode.fr/open-location-code – Mark Gavagan Dec 02 '21 at 20:47

1 Answers1

3

I didn't find the package on pub.dev, so you have to use the library I mentioned above, directly from GitHub. It is provided by Google, so it should be pretty safe and well maintained.

To do that you add it in pubspec.yaml like this:

dependencies:
  flutter:
     sdk: flutter  
  open_location_code:
     git:
       url: git://github.com/google/open-location-code.git
       path: dart

Then, in your code you import the library with:

import 'package:open_location_code/open_location_code.dart' as olc;

To convert the lat&lon to plus code you do this (creating a CodeArea object):

// Googleplex
// 1600 Amphitheatre Pkwy
// Mountain View, CA 94043  
// The coordinates of Google's Global HQ  
var codeFromLatLon = olc.encode(37.425562, -122.081812, codeLength: 1000000);
print(codeFromLatLon.toString());
// The above will print '849VCWG9+67GCC32'

To decode the plus code to lat lon you do this:

var codeFromPlusCode = olc.decode('849VCWG9+67GCC32');
print(codeFromPlusCode.toString());
// The above will print:
// CodeArea(south:37.425562, west:-122.08181201171875, north:37.42556204, east:-122.08181188964843, codelen: 15)

In order to access the lat&lon you'll have to do the following:

print('Lat: ${codeFromPlusCode.center.latitude}, Lon: ${codeFromPlusCode.center.longitude}');

Note that you can limit the length to 10 when you encode the lat&lon pair in your plus code. This will give you a shorter code, but a less accurate positioning:

var codeFromLatLonShorter = olc.encode(37.425562, -122.081812, codeLength: 10);
print(codeFromLatLonShorter.toString());
// The above will print '849VCWG9+67'

Hope the above will help. Here is a detailed explanation.

Constantin
  • 601
  • 5
  • 14