嗨,我正在使用google place api javascript sdk,并想使用ROR将结果保存到我的数据库中-我想知道四天前,它成功保存了lat / lng,但是现在将其保存为null。以下是我的解释

我在我的JavaScript中有此代码

places = new google.maps.places.PlacesService(map);
places.nearbySearch(request, callback);

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
      clearMarkers();
//alert(JSON.stringify(results));

$.ajax({
  url: "/myurl",
  data:{
    'google_searched_locations': JSON.stringify(results)
  },
  dataType: "json",
  method: 'post',
  async : false,
  success: function(data){

  }
  });
}

在回调函数中,当我执行console.log(results[0].geometry.location.lng());时,我将结果显示为74.30889000000002
console.log(results[0]);

输出
geometry
  Object { location=L}
location

L       { lat=function(),  lng=function(),  toString=function(),  more...}
equals  function(a)
j       function(a)
lat     function()
lng     function()
toString function()

这显然是有道理的。但是在firefox的控制台中,ajax数据参数以以下形式显示数据
[{"geometry":{"location":{}}]

为了清楚起见,我跳过了其他参数,因为请求中存在其他所有内容。但是您可以看到位置完全是
空的,为什么呢?以及如何在位置对象中与一起发送results[0].geometry.location.lng()

最佳答案

由于“附近的搜索请求”返回 location google.maps.LatLng type属性,并且为了保存它而需要显式序列化,因此会发生以下情况:



您可以为此引入一个新属性来存储位置字符串表示形式,如下所示:

var results = results.map(function(item){
         item.geometry.locationString = item.geometry.location.toString(); //string represenation of location property
         return item;
});

示例

function initialize() {
    var pyrmont = new google.maps.LatLng(-33.8665, 151.1956);

    var map = new google.maps.Map(document.getElementById('map'), {
        center: pyrmont,
        zoom: 15,
        scrollwheel: false
    });

    // Specify location, radius and place types for your Places API search.
    var request = {
        location: pyrmont,
        radius: '500',
        types: ['store']
    };

    // Create the PlaceService and send the request.
    // Handle the callback with an anonymous function.
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, function (results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {


           //serialize location to string
           var results = results.map(function(item){
                item.geometry.locationString = item.geometry.location.toString();
                return item;
           });

           document.getElementById('output').innerHTML = JSON.stringify(results, null, 2);
        }
    });
}

// Run the initialize function when the window has finished loading.
google.maps.event.addDomListener(window, 'load', initialize);
   html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #map {
            height: 100%;
        }
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=places"></script>
<div id="map"></div>
<pre id="output"></pre>

10-08 16:22