4

I am using DirectionsDisplay returned by Google Map JS APIv3 to get coordinates of some locations. The DirectionsDisplay has functions to return the values (lat() and lng()) but I need to send them to PHP serialized by JSON.stringify so I assign the values to new variables (cLat and cLon):

var steps=directionsDisplay.getDirections().routes[0].legs[0].steps;
for(var i=0;i<steps.length;i++){
  steps[i].end_location.cLat = steps[i].end_location.lat();
  steps[i].end_location.cLon = steps[i].end_location.lng();
}

console.log(steps) displays cLat and cLon as expected:

Object {steps: Array[8]}
  steps: Array[8]
    0: Object
      distance: Object
      duration: Object
      encoded_lat_lngs: "..."
      end_location: _.L
        cLat: 64.49756909999999    //here
        cLon: 14.148118999999951   //here
        lat: function()
        lng: function()
        __proto__: _.L
        ...

However, console.log(JSON.stringify(steps)) displays this:

{
  "steps":[
    {
      "distance":{
        "text":"132 km",
        "value":132266
      },
      "duration":{
        "text":"1 hodín, 34 minút",
        "value":5639
      },
      "end_location":{
        "lat":64.49756909999999,    //here
        "lng":14.148118999999951    //here
      },

      ...
    }
  ]
}

What am I doing wrong?

1 Answer 1

3

Take a look at the relevant part from json2.js:

// If the value has a toJSON method, call it to obtain a replacement value.

    if (value && typeof value === 'object' &&
            typeof value.toJSON === 'function') {
        value = value.toJSON(key);
    }

start_location and end_location does have a method toJSON, so these properties will be set to the returnValue of this function in JSON.stringify()

One option would be to completely overwrite the start_location and end_location

for(var i=0;i<steps.length;i++){
  steps[i].end_location=    {
                             clat:steps[i].end_location.lat(),
                             cllng:steps[i].end_location.lng()
                            };
  steps[i].start_location=  {
                             clat:steps[i].start_location.lat(),
                             clng:steps[i].start_location.lng()
                            };

  steps[i].end_location.cLon = steps[i].end_location.lng();
} 

But there is no need to to this(there also may be issues when the API needs to access these properties again).

As you see in the stringified steps they already contain the desired informations (lat and lng), just use them in your PHP-script instead of your custom properties.

Sign up to request clarification or add additional context in comments.

Comments

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.