【问题标题】:How to get location coordinates knowing place_id via google javascript api如何通过google javascript api获取知道place_id的位置坐标
【发布时间】:2015-06-21 23:20:17
【问题描述】:

我知道place_id,我需要知道它的坐标。

我可以GET https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE

这给了我类似的东西:

```   "results" : [
      {
         "address_components" : [...],
         "formatted_address" : "New York County, NY, USA",
         "geometry" : {
            "bounds" : {...},
            "location" : {
               "lat" : 40.7830603,
               "lng" : -73.9712488
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {...}
         },
         "partial_match" : true,
         "place_id" : "ChIJOwE7_GTtwokRFq0uOwLSE9g",
         "types" : [...]
      }
   ],
   "status" : "OK"
```

但我需要通过 javascript api 来完成。

我的页面上没有任何地图,只需要获取坐标。

【问题讨论】:

    标签: google-maps google-maps-api-3 google-geocoder


    【解决方案1】:

    来自the example in the Google Maps Javascript API v3 documentation(带有您的place_id):

    var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    
    service.getDetails(request, function(place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
        });
        map.fitBounds(place.geometry.viewport);
      }
    });
    

    working fiddle

    代码sn-p:

    var geocoder;
    var map;
    
    function initialize() {
      var map = new google.maps.Map(
        document.getElementById("map_canvas"), {
          center: new google.maps.LatLng(37.4419, -122.1419),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      var request = {
        placeId: 'ChIJOwE7_GTtwokRFq0uOwLSE9g'
      };
    
      var infowindow = new google.maps.InfoWindow();
      var service = new google.maps.places.PlacesService(map);
    
      service.getDetails(request, function(place, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location
          });
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(place.name);
            infowindow.open(map, this);
          });
          map.fitBounds(place.geometry.viewport);
        }
      });
    
    }
    google.maps.event.addDomListener(window, "load", initialize);
    html,
    body,
    #map_canvas {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="map_canvas" style="border: 2px solid #3872ac;"></div>

    【讨论】:

      【解决方案2】:

      您不需要地图。它是一个返回 JSON 字符串的 Restful Web 服务。在你的应用中,你只需要发送一个 HTTP 请求到

      获取https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE

      然后解析返回的JSON字符串,取回里面的latlng。

      如果您在 Web 应用程序中使用 Jquery,则可以这样做

          $.ajax({
                  type: "GET",
                  url: "https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE",
                  dataType: "text", 
                  success: function (yourJSONstring){
                      var respJson = $.parseJSON(yourJSONstring);  
      
                  // then something like ... 
                  // respJson.results[0].geometry.location.lat;
                  // respJson.results[0].geometry.location.lng; 
      
      
                  },
                  error: function (xhr) {
                  }
              }); 
      

      【讨论】:

      • 我看不出这个答案被赞成的原因。 OP 说 but I need to do it via javascript api. 但这个答案没有显示。
      【解决方案3】:

      发生这种情况是因为 location 属性的类型为 google.maps.LatLng

      您可以使用以下函数来获取 lat 和 lng: 示例:

      place.geometry.location.any_function_below()
      
      1. toString():  Converts to string representation.eg ((37.8042802, -122.41364429999999))
      2. lat(): Returns the latitude in degrees.
      3. lng(): Returns the longitude in degrees.
      4. toJSON(): Converts to JSON representation ({lat: "", lng: ""}).
      5. toUrlValue(precision?:number): Returns a string of the form "lat,lng" for this LatLng. We round the lat/lng values to 6 decimal places by default.
      

      您可以在此处阅读更多信息:https://developers.google.com/maps/documentation/javascript/3.exp/reference#LatLng

      【讨论】:

        【解决方案4】:
        `//only add these line under function`
        autocomplete.addListener('place_changed', function() {
        var place = autocomplete.getPlace();
        autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address']);
        var lng = place.geometry.location.lng();
        var lat = place.geometry.location.lat();
        var latlng = {lat , lng};
        console.log(latlng);
        

        });

        【讨论】:

        • 实际上先生,如果您使用此代码 sn-p [developers.google.com/maps/documentation/javascript/examples/… remove setFields that under origin-input and destination-input.use above function autocomplete.addListener that has been given but add autocomplete.setFields (['place_id', 'geometry', 'name', 'formatted_address']); var lng = place.geometry.location.lng(); var lat = place.geometry.location.lat(); var latlng = {lat , lng};console.log(latlng);
        【解决方案5】:

        你可以像这样检索它的位置

        var obj = JSON.parse(yourJSONstring);
        
        
        obj.results[0].geometry.location.lat;
        obj.results[0].geometry.location.lng; 
        

        【讨论】:

        • 问的不是这个
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-14
        • 2013-06-08
        • 1970-01-01
        • 2021-07-04
        • 2013-10-31
        • 1970-01-01
        相关资源
        最近更新 更多