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个回答

0
Google出于某种原因在“优化”中建议使用他们的地理编码服务而不是文本搜索。我将不得不回答与此相关的其他stackoverflow问题。提供的代码使用了Web服务,因为我正在编写一个React Native应用程序,但你可以很容易地进行调整。
const GOOGLE_MAPS_BASE = 'https://maps.googleapis.com/maps/api';
const GOOGLE_MAPS_API_KEY = 'https://console.cloud.google.com/apis/credentials';

// example code, remember to add error handling for your code
async function searchAndGetCoordExample() {
    const results = await placeSearch('Fiera Capital Toronto');
    const coordinates = [results[0].geometry.location.lat, results[0].geometry.location.lng];
}

export async function placeSearch({ query, language = 'en', limit = 10, lat, lon } = {}) {
    /*
    https://developers.google.com/maps/documentation/places/web-service/search-text
    */
    const locationParam = (lat !== undefined && lon !== undefined) ? `&location=${lat},${lon}` : '';

    const params = new URLSearchParams({
        query,
        language,
        key: GOOGLE_MAPS_API_KEY,
    });

    return await fetchTimeout(`${GOOGLE_MAPS_BASE}/place/textsearch/json?input=${params.toString()}${locationParam}&key=${GOOGLE_MAPS_API_KEY}`).then(r => r.json());
}

async function fetchTimeout(resource, options = {}) {
    // set timeout to 8 seconds from 300 seconds
    // throws Timeout error (error.name === 'AbortError')
    const { timeout = 8000 } = options;
    options.headers = { 'User-Agent': 'MyApp', ...options.headers }
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);
    const response = await fetch(resource, {
        ...options,
        signal: controller.signal
    });
    clearTimeout(id);
    return response;
}

0

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>

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