62

地図を表示せずにオートコンプリートGoogleマップ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>

4

11 に答える 11

141

以下のコードを使用できます。

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

お役に立てば幸いです。

于 2012-11-23T13:09:28.630 に答える
5

はい、できます:

var place = autocomplete.getPlace();

document.getElementById('lat').value = place.geometry.location.lat();
document.getElementById('lon').value = place.geometry.location.lng();
于 2016-10-10T12:46:28.960 に答える
1

Google Places APIは、Placesオートコンプリートを含むRESTAPIも提供します。 https://developers.google.com/places/documentation/autocomplete

ただし、サービスから取得するデータはマップに使用する必要があります。

于 2012-11-20T17:35:25.290 に答える