2015-04-22 73 views
-1

我需要用戶能夠在文本字段中輸入地址,Google可以通過用戶正在輸入的位置自動填充此地址,同時我需要知道此地理位置。鍵入文本字段 - 猜測位置

我是否認爲我需要使用Google的「Places autocomplete」或者是否有可能錯過的其他庫?

回答

1

我已使用Google的自動填充功能實現了此功能。在這裏你可以看到AngularJS的例子:

 var geocoder = new google.maps.Geocoder(); 
    function geocodePosition(pos) { 
    geocoder.geocode({ 
     latLng: pos 
    }, function(responses) { 
     if (responses && responses.length > 0) { 
     updateMarkerAddress(responses[0].formatted_address); 
     } else { 
     updateMarkerAddress('Cannot determine address at this location.'); 
     } 
    }); 
    } 

    // Create the autocomplete object, restricting the search 
    // to geographical location types. 
    var autocomplete = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */(document.getElementById('autocomplete')), 
    { types: ['geocode'] }); 
    // When the user selects an address from the dropdown, 
    // populate the address fields in the form. 
    google.maps.event.addListener(autocomplete, 'place_changed', function() { 
    var place = autocomplete.getPlace(); 
    map.setCenter(place.geometry.location); 
    scope.location = place.formatted_address; 

    }); 

    // Bias the autocomplete object to the user's geographical location, 
    // as supplied by the browser's 'navigator.geolocation' object. 
    function geolocate() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position) { 
     var geolocation = new google.maps.LatLng(
      position.coords.latitude, position.coords.longitude); 
     var circle = new google.maps.Circle({ 
      center: geolocation, 
      radius: position.coords.accuracy 
     }); 
     autocomplete.setBounds(circle.getBounds()); 
     }); 
    } 
    }