Parse JSON String By Comma Deliminator Flutter

I have some string that I need to separate into Latitude and Longitude to get LatLng but, do not know how to separate by delimiter to pull it off.

The string is: {location: 40.748817,-73.985428}

I need to separate it into Lat and lng to create a marker and do not know how

Upvotes: 0

Views: 630

Answers (3)

lrn
lrn

Reputation: 71623

Depending on what the actual input format is, it can be easier or harder.

If the input is actually a JSON map with the format {"location": "40.748817,-73.985428"}, then just parse it as JSON first, then split the string on the comma:

List<double> parseCoordinates(String source) {
  var parts = jsonParse(source)["location"]?.split(",");
  if (parts == null || parts.length != 2) {
    throw FormatException("Not valid location coordinates", source);
  }
  return [double.parse(parts[0], double.parts[1])];
}

If the input is actually a string of the form {location: 40.748817,-73.985428}, which is not valid JSON, then it looks like something which is actually most easily solved with a RegExp.

Example:

final _coordRE = RegExp(r"^\{location: (-?\d+(?:.\d+)), (-?\d+(?:.\d+))\}$");
List<double> parseCoordinates2(String source) {
  var match = _coordRE.firstMatch(source);
  if (match == null) throw FormatException("Not valid coordinates", source);
  return [double.parse(match[1]), double.parse(match[2])];
}

and then use it as

var coords = parseCoordinates(source);
var lat = coords[0];
var lng = coords[1];

Alternatively, since you know the format so precisely, you can just extract the substrings yourself instead of using a RegExp:

List<double> parseCoordinates(String source) {
  var prefix = "{location: ";
  if (source.startsWith(prefix) && source.endsWith("}")) {
    var commaIndex = source.indexOf(",", prefix.length);
    if (commaIndex >= 0) {
      var lat = double.parse(source.substring(prefix.length, commaIndex));
      var lng = double.parse(source.substring(commaIndex + 1, source.length - 1));
      return [lat, lng];
    }
  }
  throw FormatException("Not valid coordinates", source);
}

If the format can vary more than your example (perhaps it allows -.5 as a coordinate, with no leading 0), you'll have to adapt the regexp. One option is to have the capture groups simply capture [-.\d]+ and rely on the double parser to handle syntax errors.

Upvotes: 1

Cam Luc
Cam Luc

Reputation: 1

Have you tried the function jsonDecode? It returns a dynamic.

var coordinate = jsonDecode('[your json string]');

print(coordinate['location']);

Then the rest is just to split it into tokens with split() function. G'luck.

Upvotes: 0

Naveen Avidi
Naveen Avidi

Reputation: 3073

Try this !

//If String
    String location = 'location: 40.748817,-73.985428';
     List<String> latAndLong =
        location.replaceFirst(' ', '').replaceAll('location:', '').split(',');
    LatLng latLng = new LatLng(double.parse(latAndLong[0]),double.parse(latAndLong[1]));

    //If Map/JSON
    var location2 = {'location': '40.748817,-73.985428'};
    String locationExtracted = location2['location'].toString();
    List<String> latAndLong2 =
        locationExtracted.replaceFirst(' ', '').replaceAll('location:', '').split(',');
    LatLng latLng2 = new LatLng(double.parse(latAndLong2[0]),double.parse(latAndLong2[1]));

Upvotes: 1

Related Questions