【问题标题】:Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?Google Maps API - 如何在不显示地图的情况下从自动完成获取纬度和经度?
【发布时间】:2012-11-08 20:11:42
【问题描述】:

我正在尝试从 Autocomplete Google Maps API 获取纬度和经度,但不显示地图。在我的脚本中,自动补全效果很好,但我无法获得纬度和经度。

    <script type="text/javascript">
       function initialize() {
    
     var options = {
      types: ['(cities)']
     };
    
     var input = document.getElementById('searchTextField');
     var autocomplete = new google.maps.places.Autocomplete(input, options);
    }
       google.maps.event.addDomListener(window, 'load', initialize);
    
       var geocoder = new google.maps.Geocoder();
        var address = autocomplete;
    
    geocoder.geocode( { 'address': address}, function(results, status) {
    
      if (status == google.maps.GeocoderStatus.OK) {
        var latitude = results[0].geometry.location.lat();
        var longitude = results[0].geometry.location.lng();
        alert(latitude);
      } 
    }); 
    
    </script>

【问题讨论】:

    标签: javascript google-maps-api-3 autocomplete latitude-longitude


    【解决方案1】:

    Youtube 视频:https://youtu.be/8QYiGuq5LG4 这将有助于在不显示 gmap 的情况下获得纬度/经度。

     <!DOCTYPE html>
        <html>
            <head>
            <title>Place Autocomplete With Latitude & Longitude </title>
            <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
            <meta charset="utf-8">
            <style>
        #pac-input {
            background-color: #fff;
            padding: 0 11px 0 13px;
            width: 400px;
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            text-overflow: ellipsis;
        }
        #pac-input:focus {
            border-color: #4d90fe;
            margin-left: -1px;
            padding-left: 14px;  /* Regular padding-left + 1. */
            width: 401px;
        }
        }
        </style>
             <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=[YOUR-KEY]"></script> 
            <script>
        
        
          function initialize() {
                var address = (document.getElementById('pac-input'));
                var autocomplete = new google.maps.places.Autocomplete(address);
                autocomplete.setTypes(['geocode']);
                google.maps.event.addListener(autocomplete, 'place_changed', function() {
                    var place = autocomplete.getPlace();
                    if (!place.geometry) {
                        return;
                    }
        
                var address = '';
                if (place.address_components) {
                    address = [
                        (place.address_components[0] && place.address_components[0].short_name || ''),
                        (place.address_components[1] && place.address_components[1].short_name || ''),
                        (place.address_components[2] && place.address_components[2].short_name || '')
                        ].join(' ');
                }
                /*********************************************************************/
                /* var address contain your autocomplete address *********************/
                /* place.geometry.location.lat() && place.geometry.location.lat() ****/
                /* will be used for current address latitude and longitude************/
                /*********************************************************************/
                document.getElementById('lat').innerHTML = place.geometry.location.lat();
                document.getElementById('long').innerHTML = place.geometry.location.lng();
                });
          }
        
           google.maps.event.addDomListener(window, 'load', initialize);
        
            </script>
            </head>
            <body>
        <input id="pac-input" class="controls" type="text"
                placeholder="Enter a location">
        <div id="lat"></div>
        <div id="long"></div>
        </body>
        </html>
    

    【讨论】:

      【解决方案2】:
      <!DOCTYPE html>
      <html>
      <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDB1ujwvkFEo87xhHyHhHP52iJ6zMlbB_w&libraries=places&callback=initMap" async defer></script>
       
      </head>
      <body>
      
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
      
      <input type="text" id="Lat"  />
      <input type="text" id="Lng"  /> 
      
      </body>
      
      
      
      <script type="text/javascript">
          function initialize() {
              var input = document.getElementById('searchTextField');
              var autocomplete = new google.maps.places.Autocomplete(input);
              google.maps.event.addListener(autocomplete, 'place_changed', function () {
                  var place = autocomplete.getPlace();
                  document.getElementById('Lat').value = place.geometry.location.lat();
                  document.getElementById('Lng').value = place.geometry.location.lng();
              });
          }
          google.maps.event.addDomListener(window, 'load', initialize); 
      </script>
      </html>
      

      【讨论】:

      • 它肯定会工作。如果您有 google api 密钥,请用我的密钥替换您的密钥..谢谢
      • 您可以为您的 API 密钥设置限制。
      【解决方案3】:

      到 2020 年底,这很简单,如下所示。

      要在从地点下拉列表中选择的地点上显示geometry 键,应使用setFields() 方法在Autocomplete 对象实例上设置字段geometry

      代码应该是这样的。

      加载 API 库:

      <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete"
      

      初始化自动完成并处理所选地点数据,通常与上述所有答案相同。但是使用autocomplete.setFields(['geometry']) 来获取坐标;

      const autocomplete;
      
      // Init the autocomplete object
      function initAutocomplete() {
          autocomplete = new window.google.maps.places.Autocomplete(
              document.getElementById('current_location'), { types: ["geocode"] }
          );
      
          // !!! This is where you set `geometry` field to be returned with the place.
          autocomplete.setFields(['address_component', 'geometry']); // <--
      
          autocomplete.addListener("place_changed", fillInAddress);
      }
      
      // Process the address selected by user
      function fillInAddress() {
          const place = autocomplete.getPlace();
      
          // Here you can get your coordinates like this
          console.log(place.geometry.location.lat());
          console.log(place.geometry.location.lng());
      }
      

      请参阅 Autocomplete.setFieldsgeometry option 上的 Google API 文档。

      【讨论】:

        【解决方案4】:

        HTML:

        <input type="text" id="address" name="address" value=""> //Autocomplete input address
        
        <input type="hidden" name="s_latitude" id="s_latitude" value="" /> //get latitude
        <input type="hidden" name="s_longitude" id="s_longitude" value="" /> //get longitude
        

        Javascript:

        <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
        async defer></script>
        
        <script>
        var input = document.getElementById('address');
        var originLatitude = document.getElementById('s_latitude');
        var originLongitude = document.getElementById('s_longitude');
        
        var originAutocomplete = new google.maps.places.Autocomplete(input);
        
            
        originAutocomplete.addListener('place_changed', function(event) {
            var place = originAutocomplete.getPlace();
        
            if (place.hasOwnProperty('place_id')) {
                if (!place.geometry) {
                        // window.alert("Autocomplete's returned place contains no geometry");
                        return;
                }
                originLatitude.value = place.geometry.location.lat();
                originLongitude.value = place.geometry.location.lng();
            } else {
                service.textSearch({
                        query: place.name
                }, function(results, status) {
                    if (status == google.maps.places.PlacesServiceStatus.OK) {
                        originLatitude.value = results[0].geometry.location.lat();
                        originLongitude.value = results[0].geometry.location.lng();
                    }
                });
            }
        });
        </script>
        

        【讨论】:

          【解决方案5】:

          您可以使用下面的代码。

          <script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>
          
          <script type="text/javascript">
              function initialize() {
                  var input = document.getElementById('searchTextField');
                  var autocomplete = new google.maps.places.Autocomplete(input);
                  google.maps.event.addListener(autocomplete, 'place_changed', function () {
                      var place = autocomplete.getPlace();
                      document.getElementById('city2').value = place.name;
                      document.getElementById('cityLat').value = place.geometry.location.lat();
                      document.getElementById('cityLng').value = place.geometry.location.lng();
                      //alert("This function is working!");
                      //alert(place.name);
                     // alert(place.address_components[0].long_name);
          
                  });
              }
              google.maps.event.addDomListener(window, 'load', initialize); 
          </script>
          

          这部分在您的表单中:

          <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
          <input type="hidden" id="city2" name="city2" />
          <input type="hidden" id="cityLat" name="cityLat" />
          <input type="hidden" id="cityLng" name="cityLng" />  
          

          希望对你有帮助。

          【讨论】:

          • 如何将国家和行政区域添加到此解决方案中?我想要国家、行政区域(州)、城市、经纬度。
          【解决方案6】:

          您可以从地点对象获取 lat、lng,即

          var place = autocomplete.getPlace();
          
          var latitude = place.geometry.location.lat();
          var longitude = place.geometry.location.lng();
          

          【讨论】:

            【解决方案7】:

            只需要:

            var place = autocomplete.getPlace();
            // get lat
            var lat = place.geometry.location.lat();
            // get lng
            var lng = place.geometry.location.lng();
            

            【讨论】:

            • 谢谢伙计。工作一种享受。只是指出autocompletenew google.maps.places.Autocomplete(nativeElement创建的对象,options)`
            【解决方案8】:

            是的,你可以:

            var place = autocomplete.getPlace();
            
            document.getElementById('lat').value = place.geometry.location.lat();
            document.getElementById('lon').value = place.geometry.location.lng();
            

            【讨论】:

              【解决方案9】:

              您无需任何额外的 api 或 url 调用即可从同一个 api 获取。

              HTML

              <input class="wd100" id="fromInput" type="text" name="grFrom" placeholder="From" required/>
              

              Javascript

              var input = document.getElementById('fromInput');
              var defaultBounds = new google.maps.LatLngBounds(
                  new google.maps.LatLng(-33.8902, 151.1759),
                  new google.maps.LatLng(-33.8474, 1512631)
              )
              
              var options = {
              bounds: defaultBounds   
              }
              
              var autocomplete = new google.maps.places.Autocomplete(input, options);
              var searchBox = new google.maps.places.SearchBox(input, {
                       bounds: defaultBounds
              });
              
              
              google.maps.event.addListener(searchBox, 'places_changed', function() {
                  var places = searchBox.getPlaces();
              
              
              console.log(places[0].geometry.location.G); // Get Latitude
              console.log(places[0].geometry.location.K); // Get Longitude
              
              //Additional information
              console.log(places[0].formatted_address); // Formated Address of Place
              console.log(places[0].name); // Name of Place
              
              
              
              
              
              
                  if (places.length == 0) {
                    return;
                  }
              
                  var bounds = new google.maps.LatLngBounds();
                  console.log(bounds);
                   });
                 }
              

              【讨论】:

                【解决方案10】:

                您无法从自动完成 API 获取纬度/经度,因为谷歌从该 API 生成的数据不包含纬度和对数字段。 示例:-

                {
                   "predictions" : [
                      {
                         "description" : "IIT Mumbai, Mumbai, Maharashtra, India",
                         "id" : "ac3235cda973818a89b5fe21ad0f5261ac9b6723",
                         "matched_substrings" : [
                            {
                               "length" : 10,
                               "offset" : 0
                            }
                         ],
                         "reference" : "CkQ0AAAAHWg-RSngiYHHdz_yqyFKmfSoBwT-_PW0k8qQDhsbiVrk7BlPHCyJb58OthledMUTGYS5Vhec1Zj2L7w9Rq0zDxIQrbn05RX1QgWHkSXsmTk1TRoU45APW2BBRIUsA3t6XBy_8s0BPPA",
                         "terms" : [
                            {
                               "offset" : 0,
                               "value" : "IIT Mumbai"
                            },
                            {
                               "offset" : 12,
                               "value" : "Mumbai"
                            },
                            {
                               "offset" : 20,
                               "value" : "Maharashtra"
                            },
                            {
                               "offset" : 33,
                               "value" : "India"
                            }
                         ],
                         "types" : [ "establishment", "geocode" ]
                      }
                   ],
                   "status" : "OK"
                }
                

                您可以使用 Google API 从您的地址获取经度和纬度。正如您已经说过的,您应该在应该插入结果的地方实现一个隐藏字段。然后您可以将位置与坐标一起保存。

                例如https://maps.googleapis.com/maps/api/geocode/json?address=IIT%20Area,%20Mumbai,%20Maharashtra,%20India&sensor=false

                我最近在我的一个项目中实现了这个功能:

                function getLatLngFromAddress(city, country){
                
                  var address = city +", "+ country;
                  var geocoder = new google.maps.Geocoder();
                
                  geocoder.geocode( { 'address': address}, function(results, status) {
                
                    if (status == google.maps.GeocoderStatus.OK) {
                      $('#latitude').val(results[0].geometry.location.Pa);
                      $('#longitude').val(results[0].geometry.location.Qa);
                
                    } else {
                      console.log("Geocode was not successful for the following reason: " + status);
                    }
                  });
                }
                

                【讨论】:

                【解决方案11】:

                Google Places API 还提供 REST api,包括 Places Autocomplete。 https://developers.google.com/places/documentation/autocomplete

                但从服务中检索的数据必须用于地图。

                【讨论】:

                • 现在看来不是这样。 Google API 文档说:“即使没有地图,您也可以使用 Place Autocomplete。如果您显示地图,它必须是 Google 地图。当您在没有地图的情况下显示 Place Autocomplete 服务的预测时,您必须包括 'powered由谷歌的标志。”这取自 API 文档:developers.google.com/places/documentation/autocomplete
                • (d) 不可用于非 Google 地图。客户不得在包含非 Google 地图的客户应用程序中使用 Google 地图核心服务。例如,客户不会 (i) 在非 Google 地图上显示 Places 列表,或 (ii) 在同一客户应用程序中显示街景图像和非 Google 地图。您不能将地点 API 数据用于与地图无关的目的。您可以在应用中实现地点自动填充功能,但不能将其用于(重复使用)其他用途,例如广告列表。
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2012-01-22
                • 2011-11-27
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-06-13
                • 2016-04-07
                相关资源
                最近更新 更多