Makoto
Makoto

Reputation: 1475

Convert String to LatLng

I'm using Google Maps API v2 and I get a location coordinates single String "-34.8799074,174.7565664" from my SharedPreferences that I need to convert to LatLng.

Can anyone help with this please?

Thx!

Upvotes: 22

Views: 69528

Answers (3)

Tony-17
Tony-17

Reputation: 1

String convert = "-34.8799074,174.7565664";
Location location = new Location(convert);
LatLng location2 = new LatLng(location.getLatitude(),location.getLongitude());

Upvotes: -1

display name
display name

Reputation: 4185

[Google Maps Android API]

You can split the string by comma and then parse the string to long

String[] latlong =  "-34.8799074,174.7565664".split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);

To constructs a LatLng with the given latitude and longitude coordinates

LatLng location = new LatLng(latitude, longitude);

[Google Maps JavaScript API]

To do same operation with Maps JavaScript API service (JSFiddle demo) -

  var latlong =  '-34.397,150.644'.split(',');
  var latitude = parseFloat(latlong[0]);
  var longitude = parseFloat(latlong[1]);
  var mapOptions = {
    zoom: 8,
    center: {lat: latitude, lng: longitude}
  };

Upvotes: 55

edwoollard
edwoollard

Reputation: 12335

Firstly you will want to split the string on the comma:

String[] latLng = "-34.8799074,174.7565664".split(",");

This will then give you two String variables, which you will want to parse as doubles like so because the LatLng constructor takes two doubles for the latitude and longitude of the location:

double latitude = Double.parseDouble(latLng[0]);
double longitude = Double.parseDouble(latLng[1]);

Finally, adding to the previous answer, you will then want to put these into a LatLng object which is the class frequently used by Google Maps:

LatLng location = new LatLng(latitude, longitude);

Upvotes: 16

Related Questions