Javascript 谷歌地图API-如何在不显示地图的情况下从自动完成中获取纬度和经度?

Javascript 谷歌地图API-如何在不显示地图的情况下从自动完成中获取纬度和经度?,javascript,google-maps-api-3,autocomplete,latitude-longitude,Javascript,Google Maps Api 3,Autocomplete,Latitude Longitude,我试图在不显示地图的情况下从自动完成的谷歌地图API中获取纬度和经度。在我的脚本中,自动完成工作得很好,但我无法获得纬度和经度 函数初始化(){ 变量选项={ 类型:['(城市)] }; var input=document.getElementById('searchTextField'); var autocomplete=new google.maps.places.autocomplete(输入,选项); } google.maps.event.addDomListener(窗口“加

我试图在不显示地图的情况下从自动完成的谷歌地图API中获取纬度和经度。在我的脚本中,自动完成工作得很好,但我无法获得纬度和经度


函数初始化(){
变量选项={
类型:['(城市)]
};
var input=document.getElementById('searchTextField');
var autocomplete=new google.maps.places.autocomplete(输入,选项);
}
google.maps.event.addDomListener(窗口“加载”,初始化);
var geocoder=new google.maps.geocoder();
var地址=自动完成;
geocoder.geocode({'address':address},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK){
var latitude=results[0]。geometry.location.lat();
var longitude=results[0]。geometry.location.lng();
警报(纬度);
} 
}); 

Google Places API还提供REST API,包括Places自动完成。


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

您可以使用下面的代码

<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>

函数初始化(){
var input=document.getElementById('searchTextField');
var autocomplete=new google.maps.places.autocomplete(输入);
google.maps.event.addListener(自动完成,'place\u changed',函数(){
var place=autocomplete.getPlace();
document.getElementById('city2')。value=place.name;

document.getElementById('cityla')。value=place.geometry.location.lat(); document.getElementById('cityLng')。value=place.geometry.location.lng(); //警报(“此功能正在工作!”); //警报(地点、名称); //警报(place.address\u组件[0]。long\u名称); }); } google.maps.event.addDomListener(窗口“加载”,初始化);
这部分在您的表单中:

<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" />  


我希望它能有所帮助。

您无法从自动完成API获取纬度/经度,因为google从该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"
}
您可以使用GoogleAPI从您的地址获取经度和纬度。正如您已经说过的,您应该在插入结果的地方实现一个隐藏字段。然后可以将位置与坐标一起保存

e、 g

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

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

您可以从同一个api获取数据,而无需任何额外的api或url调用

HTML

是的,你可以:

var place = autocomplete.getPlace();

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

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

您可以从place对象(即

var place = autocomplete.getPlace();

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

//自动完成输入地址
//获得自由
//获得经度
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>

var input=document.getElementById('address');
var originLatitude=document.getElementById('s_latitude');
var originLongitude=document.getElementById('s_-longitude');
var originAutocomplete=新的google.maps.places.Autocomplete(输入);
originAutocomplete.addListener('place\u changed',函数(事件){
var place=originAutocomplete.getPlace();
if(place.hasOwnProperty('place\u id')){
如果(!place.geometry){
//警告(“自动完成的返回位置不包含几何体”);
返回;
}

originLatitude.value=place.geometry.location.lat(); originLongitude.value=place.geometry.location.lng(); }否则{ service.textSearch({ 查询:place.name },功能(结果、状态){ if(status==google.maps.places.PlacesServiceStatus.OK){ originLatitude.value=results[0]。geometry.location.lat(); originLongitude.value=结果[0]。geometry.location.lng(); } }); } });
根据2020年末的情况,这很简单,如下所示

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

代码应该是这样的

加载API库:


函数初始化(){
var input=document.getElementById('searchTextField');
var autocomplete=new google.maps.places.autocomplete(输入);
google.maps.event.addListener(自动完成,'place\u changed',函数(){
var place=autocomplete.getPlace();

document.getElementById('Lat')。value=place.geometry.location.Lat(); document.getElementById('Lng')。value=place.geometry.location.Lng(); }); } google.maps.event.addDomListener(窗口“加载”,初始化);
Youtube视频: 这将有助于在不显示gmap的情况下获得lat/lon

 <!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>

使用纬度和经度放置自动完成
#pac输入{
背景色:#fff;
填充:0 11px 0 13px;
宽度:400px;
字体系列:Roboto;
字体大小:15px;
字体大小:300;
文本溢出:省略号;
}
#pac输入:焦点{
边框颜色:#4d90fe;
左边距:-1px;
左填充:14px;/*常规左填充+1*/
宽度:401px;
}
}
函数初始化(){
var地址=(document.getElementById('pac-input');
var autocomplete=new google.maps.places.autocomplete(地址);
setTypes(['geocode']);
google.maps.event.addListener(自动完成,'place\u changed',函数(){
var place=autocomplete.getPlace();
如果(!place.geometry){
返回;
}
var地址=“”;
if(位置、地址和组件){
地址=[
<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
<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>
<!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>
 <!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>