Reputation: 10571
In php I push coordinates to an array in a loop:
$lat = $location['lat'];
$lng = $location['lng'];
array_push($coordinates, $lat.",".$lng);
I then need those coords as a pair in jQuery.
var coords = "<?php echo $coordinates; ?>";
console.log(coords);
The above gives me:
40.836132854296686,8.404270310882566,40.7197406,8.563512299999957,41.36256133817761,2.131976960327165
But since I need them as a pair as I later do:
for (var a = 0; a < coords.length; ++a) {
var pin = coords[a].split(',');
var latLng = new google.maps.LatLng(pin[0], pin[1]);
I don't know who to convert that string in a pair array object. I thought of adding []
as a string when I push to array in php but it's very bad.
Basically I am looking for:
["55.695694737568054,37.5904788172536", "41.36256133817761,2.131976960327165", "40.836132854296686, 8.404270310882566", "40.7197406, 8.563512299999957"]
Thought of splitting every second comma in js as per this answer but I'm not sure is the correct way.
Upvotes: 0
Views: 319
Reputation: 20039
Use JSON
PHP
$lat = $location['lat'];
$lng = $location['lng'];
array_push($coordinates, [$lat, $lng]);
JS
var coordsJson = '<?php echo json_encode($coordinates); ?>';
var coords = JSON.parse(coordsJson)
console.log(coords);
// [[40.836132854296686,8.404270310882566],[40.7197406,8.563512299999957]]
for (var a = 0; a < coords.length; ++a) {
var latLng = new google.maps.LatLng(
parseFloat(coords[a][0]),
parseFloat(coords[a][1])
);
}
Upvotes: 3