Подтвердить что ты не робот

Google map api получить Широта и долгота от автозаполнения без карты

Я пытаюсь получить широту и долготу с автозаполнения api google map, не показывая карту. В моем script автозаполнение работает хорошо, но я не могу получить широту и долготу.

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

Ответ 1

Вы можете использовать код ниже.

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

Надеюсь, это поможет.

Ответ 2

Требуется только:

var place = autocomplete.getPlace();
// get lat
var lat = place.geometry.location.lat();
// get lng
var lng = place.geometry.location.lng();

Ответ 3

Вы не можете получить широту/долготу из API автозаполнения, поскольку данные, созданные Google из этого API, не содержат поля широты и логирования. Пример: -

{
   "predictions" : [
      {
         "description" : "IIT Mumbai, Mumbai, Maharashtra, India",
         "id" : "ac3235cda973818a89b5fe21ad0f5261ac9b6723",
         "matched_substrings" : [
            {
               "length" : 10,
               "offset" : 0
            }
         ],
         "reference" : "CkQ0AAAAHWg-RSngiYHHdz_yqyFKmfSoBwT-_PW0k8qQDhsbiVrk7BlPHCyJb58OthledMUTGYS5Vhec1Zj2L7w9Rq0zDxIQrbn05RX1QgWHkSXsmTk1TRoU45APW2BBRIUsA3t6XBy_8s0BPPA",
         "terms" : [
            {
               "offset" : 0,
               "value" : "IIT Mumbai"
            },
            {
               "offset" : 12,
               "value" : "Mumbai"
            },
            {
               "offset" : 20,
               "value" : "Maharashtra"
            },
            {
               "offset" : 33,
               "value" : "India"
            }
         ],
         "types" : [ "establishment", "geocode" ]
      }
   ],
   "status" : "OK"
}

Вы можете использовать Google API для получения долготы и широты с вашего адреса. Как вы уже сказали, вы должны реализовать скрытое поле, в которое должен быть вставлен результат. Затем вы можете сохранить местоположение вместе с координатами.

e.g https://maps.googleapis.com/maps/api/geocode/json?address=IIT%20Area,%20Mumbai,%20Maharashtra,%20India&sensor=false

Недавно я реализовал эту функцию в одном из моих проектов:

function getLatLngFromAddress(city, country){

  var address = city +", "+ country;
  var geocoder = new google.maps.Geocoder();

  geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
      $('#latitude').val(results[0].geometry.location.Pa);
      $('#longitude').val(results[0].geometry.location.Qa);

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

Ответ 4

Да, вы можете:

var place = autocomplete.getPlace();

document.getElementById('lat').value = place.geometry.location.lat();
document.getElementById('lon').value = place.geometry.location.lng();

Ответ 5

Вы можете получить lat, lng из объекта place, т.е.

var place = autocomplete.getPlace();

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

Ответ 6

API Google Places также предоставляет REST api, включая автозаполнение мест. https://developers.google.com/places/documentation/autocomplete

Но данные, полученные из службы, должны использоваться для карты.

Ответ 7

Вы можете получить от одного и того же api без какого-либо дополнительного вызова api или url.

HTML

<input class="wd100" id="fromInput" type="text" name="grFrom" placeholder="From" required/>

Javascript

var input = document.getElementById('fromInput');
var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-33.8902, 151.1759),
    new google.maps.LatLng(-33.8474, 1512631)
)

var options = {
bounds: defaultBounds   
}

var autocomplete = new google.maps.places.Autocomplete(input, options);
var searchBox = new google.maps.places.SearchBox(input, {
         bounds: defaultBounds
});


google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();


console.log(places[0].geometry.location.G); // Get Latitude
console.log(places[0].geometry.location.K); // Get Longitude

//Additional information
console.log(places[0].formatted_address); // Formated Address of Place
console.log(places[0].name); // Name of Place






    if (places.length == 0) {
      return;
    }

    var bounds = new google.maps.LatLngBounds();
    console.log(bounds);
     });
   }

Ответ 8

@Override
public void onPlaceSelected(Place place) {
    LatLng autoCompleteLatLng = place.getLatLng();
    newLoc = new Location("New");
    newLoc.setLatitude(autoCompleteLatLng.latitude);
    newLoc.setLongitude(autoCompleteLatLng.longitude);

    geoLocate(newLoc);//mark it in map
}