JSON.stringify google map object

I am using the DirectionsDisplay returned by the Google Map JS APIv3 to get the coordinates of some locations. There are functions in DirectionsDisplay for returning values ​​( lat()and lng()), but I need to send them to PHP, serialized JSON.stringify, so I assign values ​​to new variables ( cLatand 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 cLatand 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, it console.log(JSON.stringify(steps))displays the following:

{
  "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?

+4
source share
1 answer

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 end_location toJSON, returnValue JSON.stringify()

- start_location 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();
} 

( , API ).

steps, (lat lng), PHP- script .

+3

Source: https://habr.com/ru/post/1630038/


All Articles