Google Maps API - 如何在不显示地图的情况下从Autocomplete获取纬度和经度?

65
我正在尝试从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>

12个回答

145
您可以使用以下代码。
<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" />  

我该如何将国家和行政区添加到这个解决方案中?我想要国家、行政区(州)、城市、纬度和经度。 - Marthinus Strydom

34

仅需:

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

谢谢,伙计。非常有效。只是要指出autocomplete是由new google.maps.places.Autocomplete(nativeElement,options)创建的对象。 - dewd

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

3
只需使用您获取的place_id进行Place Details查询。具体操作请参考https://developers.google.com/places/documentation/details。 - CallMeLaNN
3
位置.几何体.位置.纬度() - 4ndro1d

7

截至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']) 来获取坐标信息。

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

请参阅Google API文档中的Autocomplete.setFieldsgeometry选项


5
您可以从地点对象中获取纬度和经度,即:
var place = autocomplete.getPlace();

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

5

是的,您可以:

var place = autocomplete.getPlace();

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

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>

1

3
现在似乎不是这种情况。谷歌API文档中写道:“即使没有地图,您也可以使用Place Autocomplete。如果您显示地图,则必须是Google地图。当您在没有地图的情况下显示来自Place Autocomplete服务的预测时,必须包含“由Google提供支持”的徽标。” 这段话摘自API文档:https://developers.google.com/places/documentation/autocomplete - Karl Glennon
(d)不得与非Google地图一起使用。客户不得在包含非Google地图的客户应用程序中使用Google Maps核心服务。例如,客户不得(i)在非Google地图上显示地点列表,或者(ii)在同一客户应用程序中显示街景图像和非Google地图。您不能将Places API数据用于与地图无关的目的。您可以在应用程序中实现地点自动完成,但是您不能将其(重复使用)用于其他目的,例如广告列表。 - wf9a5m75

1
您可以通过同一个API获取数据,无需进行任何额外的API调用或URL请求。
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);
     });
   }

0
<!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=YOUR_API_KEY&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密钥,请用我的密钥替换它。谢谢。 - Aashir Azeem
你可以为你的 API 密钥设置限制。 - Kundan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接