0

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.

1 Answer 1

3

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])
    );
}
Sign up to request clarification or add additional context in comments.

10 Comments

Don't forget coords = JSON.parse(coords); if you want to do something with the array in Javascript.
it is giving me var coords = [["40.836132854296686","8.404270310882566"],["40.7197406","8.563512299999957"],["41.36256133817761","2.131976960327165"]];
and gives me Uncaught SyntaxError: Unexpected token , in JSON at position 18
@rob.m check this line array_push($coordinates, [$lat, $lng]);
@User863 I'm not sure why it is wrong, I am using array_push($coordinates, [$lat, $lng]);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.