2010-08-16 9 views
33

Ho una casella di testo nella mia pagina che ottiene un nome di posizione e un pulsante con il testo getLat&Long. Ora, facendo clic sul mio pulsante, devo mostrare un avviso di latitude e longitude della posizione nella casella di testo. Qualche suggerimento?Ottieni latitudine e longitudine in base al nome della posizione con l'API di completamento automatico di Google

+0

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+ CA & sensor = true maggiori informazioni qui https://developers.google.com/maps/documentation/geocoding/ – zzart

risposta

37

È possibile utilizzare la Google Geocoder service nel Google Maps API convertire da proprio nome ad una posizione di latitudine e longitudine. Quindi è necessario un po 'di codice come:

var geocoder = new google.maps.Geocoder(); 
var address = document.getElementById("address").value; 
geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) 
    { 
     // do something with the geocoded result 
     // 
     // results[0].geometry.location.latitude 
     // results[0].geometry.location.longitude 
    } 
}); 

Aggiornamento

State voi compreso il v3 API JavaScript?

<script type="text/javascript" 
    src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false"> 
</script> 
+0

Errore-'google.maps.Geocoder();' non è un costruttore. – Chandra

+0

Come posso usarlo per origine e destinazione intendo due campi ??? – Wearybands

+0

qual è il sensore di differenza vero o falso? – Serge

8

Il sotto è il codice che ho usato. Funziona perfettamente.

var geo = new google.maps.Geocoder; 
geo.geocode({'address':address},function(results, status){ 
    if (status == google.maps.GeocoderStatus.OK) {    
     var myLatLng = results[0].geometry.location; 

     // Add some code to work with myLatLng    

    } else { 
     alert("Geocode was not successful for the following reason: " + status); 
    } 
}); 

Spero che questo possa essere d'aiuto.

2

Vorrei suggerire il seguente codice, è possibile utilizzare questo <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script> per ottenere la latitudine e la longitudine di una posizione, anche se potrebbe non essere così preciso ma ha funzionato per me;

frammento di codice di seguito

<!DOCTYPE html> 
<html> 
<head> 
<title>Using Javascript's Geolocation API</title> 

<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
</head> 
<body> 
<div id="mapContainer"></div> 

<script type="text/javascript"> 

     var lat = geoip_latitude(); 
     var long = geoip_longitude(); 
     document.write("Latitude: "+lat+"</br>Longitude: "+long); 

</script> 
</body> 
</html> 
31

spero che questo può aiutare qualcuno in futuro.

È possibile utilizzare il Google Geocoding API, come detto prima, ho dovuto fare un po 'di lavoro con questa recente, spero che questo aiuta:

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script> 
     <script type="text/javascript"> 
     function initialize() { 
     var address = (document.getElementById('my-address')); 
     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(' '); 
     } 
     }); 
} 
function codeAddress() { 
    geocoder = new google.maps.Geocoder(); 
    var address = document.getElementById("my-address").value; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 

     alert("Latitude: "+results[0].geometry.location.lat()); 
     alert("Longitude: "+results[0].geometry.location.lng()); 
     } 

     else { 
     alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
    } 
google.maps.event.addDomListener(window, 'load', initialize); 

     </script> 
    </head> 
    <body> 
     <input type="text" id="my-address"> 
     <button id="getCords" onClick="codeAddress();">getLat&Long</button> 
    </body> 
</html> 

Ora, questo ha anche una funzione autocomlpete che si può vedere nel codice , recupera l'indirizzo dall'input e viene completato automaticamente dall'API durante la digitazione.

Una volta che il tuo indirizzo ha colpito il pulsante e ottieni i risultati via avviso, come richiesto. Si noti inoltre che utilizza l'ultima API e carica la libreria 'places' (quando chiama l'API utilizza il parametro 'librerie').

Spero che questo aiuti e leggere la documentazione per ulteriori informazioni, applausi.

Modifica # 1: Fiddle

+1

sì grazie! il lat() lng() è perfetto perché sembra cambiare da richiesta a richiesta in modo casuale con proprietà reali come "k" e "A" o altri strani come quello per lat lng. Sei un coool. –

+0

molto utile. Hai fatto un ottimo lavoro. Grazie – Randhir

+0

Questo richiede una chiave API? – Supertecnoboff

6

Spero che questo sarà più utile per la portata futura contiene automatica completa di funzioni API di Google con latitudine e longitudine

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

Complete View

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

Ente r la posizione in Completamento automatico e il resto di tutti i campi: i valori di latitudine e Longitudine vengono automaticamente riempiti.
Sostituire CHIAVE API con l'API di Google chiave

<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
<meta charset="utf-8"> 
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script> 

<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"> 
</head> 

<body> 
<textarea placeholder="Enter Area name to populate Latitude and Longitude" name="address" onFocus="initializeAutocomplete()" id="locality" ></textarea><br> 

<input type="text" name="city" id="city" placeholder="City" value="" ><br> 
<input type="text" name="latitude" id="latitude" placeholder="Latitude" value="" ><br> 
<input type="text" name="longitude" id="longitude" placeholder="Longitude" value="" ><br> 
<input type="text" name="place_id" id="location_id" placeholder="Location Ids" value="" ><br> 

<script type="text/javascript"> 
    function initializeAutocomplete(){ 
    var input = document.getElementById('locality'); 
    // var options = { 
    // types: ['(regions)'], 
    // componentRestrictions: {country: "IN"} 
    // }; 
    var options = {} 

    var autocomplete = new google.maps.places.Autocomplete(input, options); 

    google.maps.event.addListener(autocomplete, 'place_changed', function() { 
     var place = autocomplete.getPlace(); 
     var lat = place.geometry.location.lat(); 
     var lng = place.geometry.location.lng(); 
     var placeId = place.place_id; 
     // to set city name, using the locality param 
     var componentForm = { 
     locality: 'short_name', 
     }; 
     for (var i = 0; i < place.address_components.length; i++) { 
     var addressType = place.address_components[i].types[0]; 
     if (componentForm[addressType]) { 
      var val = place.address_components[i][componentForm[addressType]]; 
      document.getElementById("city").value = val; 
     } 
     } 
     document.getElementById("latitude").value = lat; 
     document.getElementById("longitude").value = lng; 
     document.getElementById("location_id").value = placeId; 
    }); 
    } 
</script> 
</body> 
</html> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script src="//maps.googleapis.com/maps/api/js?libraries=places&key=API KEY"></script> 


<script src="https://fonts.googleapis.com/css?family=Roboto:300,400,500></script> 
Problemi correlati