Google Maps API - 如何在不显示地图的情况下从自动完成获取纬度和经度? [英] Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

查看:22
本文介绍了Google Maps API - 如何在不显示地图的情况下从自动完成获取纬度和经度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在不显示地图的情况下从自动完成 Google 地图 API 获取纬度和经度.在我的脚本中,自动完成功能运行良好,但我无法获取纬度和经度.

I'm trying to get latitude and longitude from Autocomplete Google Maps API without showing the map. In my script autocompletion works well, but I can't get the latitude and longitude.

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

推荐答案

您可以使用下面的代码.

You can use the code below.

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

希望能帮到你.

这篇关于Google Maps API - 如何在不显示地图的情况下从自动完成获取纬度和经度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆