Reputation: 125
I have this JSON String:
"[{"lat":"42.021631","lng":"-93.624239"},{"lat":"19.112049","lng":"72.870234"}]"
I need it in this format to be able to plot using Google Maps which uses this:
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
How do I get this in the format? I've received my string after using Papa Parse to import CSV and removed the quotes in the JSON text. Any help will be appreciated.
Upvotes: 0
Views: 4183
Reputation: 1148
That isn't a valid JSON. If the string is from a trusted source, you could use eval.
var result = eval([{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}])
Will return
[Object, Object]
Upvotes: 1
Reputation: 28870
The real problem here, given the latest update to your question, is that the lat
and lng
values in your JSON data are strings instead of numbers.
In other words, where your JSON data looks like this (whitespace added for clarity):
[
{ "lat": "42.021631", "lng": "-93.624239" },
{ "lat": "19.112049", "lng": "72.870234" }
]
it should look like this:
[
{ "lat": 42.021631, "lng": -93.624239 },
{ "lat": 19.112049, "lng": 72.870234 }
]
The best way to fix this is to change your server code to generate that second format instead of the first one. I can't give specifics because I don't know what server language or libraries you are using. But if you can get the server to generate the lat
and lng
values as the numbers they should be instead of strings, everything will get easier.
If that can't be done, the solution is not to be mucking around with the JSON text, stripping out quotes or adding them back in with regular expressions. That is just creating a mess that you don't need and doesn't help you.
Instead, simply convert the lat
and lng
values to numbers where you need to.
For example, if you have the first element of your JSON array in a variable called location
, you may be trying to create a LatLng
object from it like this:
var latlng = new google.maps.LatLng( location.lat, location.lng );
That may not work, because location.lat
and location.lng
are strings, not numbers. But you can easily convert them to numbers:
var latlng = new google.maps.LatLng( +location.lat, +location.lng );
There are several ways to convert a string to a number, but the unary +
operator is the most succinct.
How does the +
operator work? It isn't specific to Google Maps or the LatLng
object or anything like that. It's simply a JavaScript operator. If you apply the +
operator to something that is already a number, it just leaves it alone. But if you apply +
to a string, it converts it to a number.
Alternatively, you could use the parseFloat
function:
var latlng = new google.maps.LatLng(
parseFloat(location.lat),
parseFloat(location.lng)
);
There's nothing wrong with that if you find it more clear, but try the +
operator: once you get used to it, you may find you like it.
Again, though, the best solution is to fix the server code to generate proper JSON numbers as illustrated above.
Upvotes: 1
Reputation: 18136
You should try to keep the quotes ...
x = "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:0},{lat:42.112049,lng:0}]".split("},{");
var regex = /[+-]?\d+(\.\d+)?/g;
flightPlanCoordinates = [];
for (var i=0; i<x.length; i++) {
coords = x[i].match(regex).map(function(v) { return parseFloat(v); });
if (coords.length === 2) {
flightPlanCoordinates.push({ "lat": coords[0], "lng": coords[1] });
}
}
console.log(flightPlanCoordinates);
Kris Roofe's answer is quite nice.
Upvotes: 1
Reputation: 161384
JSON.parse converts a JSON string to a javascript object. If you leave the quotes in so it is valid JSON:
'[{"lat":42.021631,"lng":-93.624239},{"lat":19.112049,"lng":72.870234}]'
This will create a polyline:
var path = JSON.parse('[{"lat":42.021631,"lng":-93.624239},{"lat":19.112049,"lng":72.870234}]');
console.log(path);
var polyline = new google.maps.Polyline({
map: map,
path: path
});
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var path = JSON.parse('[{"lat":42.021631,"lng":-93.624239},{"lat":19.112049,"lng":72.870234}]');
var polyline = new google.maps.Polyline({
map: map,
path: path
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
Upvotes: 2
Reputation: 589
The simplest way is eval.
var str = "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}]";
eval(str);
Upvotes: 1
Reputation: 28534
You string is not an json format, so you first translate it to json format.
let str = "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}]";
let jsonStr = str.replace(/(lat|lng)/g, '"' + "$1" + '"');
let json = JSON.parse(jsonStr);
console.log(json);
Upvotes: 2
Reputation: 3893
JSON.parse(<json string variable>)
will return a JS object that you can pass into google maps.
However: your JSON is not valid: "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}]"
. The lat and lngs should be wrapped with double quotes.
Upvotes: 2
Reputation: 309
You need to keep the quotes in the JSON text and run this line:
var flightPlanCoordinates = JSON.parse('[{"lat":"42.021631","lng":"-93.624239"},{"lat":"19.112049","lng":"72.870234"}]')
Upvotes: -1