user4239503
user4239503

Reputation:

Get from a Draggrable Marker new street and town

I've a google maps with a draggrabble marker that in infowindow show the street and town

NOw I use this code to get new lng e lat in a form when marker is dragged


var geocoder = new google.maps.Geocoder;
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
  if (results[1]) {
    infowindow.setContent(results[0].formatted_address);
    infowindow.open(map, marker);
  } else {
    window.alert('No results found');
  }
 } else {
  window.alert('Geocoder failed due to: ' + status);
 }
 });
 }

google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("lat").value = this.getPosition().lat();
document.getElementById("lng").value = this.getPosition().lng(); 
document.getElementById("latlng").value =  this.getPosition().lat()+','+this.getPosition().lng();
geocodeLatLng(geocoder, map, infowindow);
});

In the input lng, lat, latlng all is ok so the value change moving the marker, but I can determine the value of 2 other input that are city and street

I'm looking for something like

document.getElementById("address").value = this.address;
document.getElementById("city").value = this.city;

Upvotes: 0

Views: 82

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133400

The result components contain element organized in this way

results[0].components

filtering n.th result[0].components[n].types by the

  • route matches long or short name of a route.

  • locality matches against both locality and sublocality types.

  • administrative_area matches all the administrative_area levels (administrative_area_level_3.political = town/city , administrative_area_level_2.political = province/county, administrative_area_level_1.political = country)

  • postal_code matches postal_code and postal_code_prefix.

  • country matches a country name or a two letter ISO 3166-1 country code.

you can get what you need in

   result[0].components[n].long_name

if you want only locality you should iterate this way

  for  (var i=0;  i < results[0].address_components.length; i++ ) {
      if (results[0].address_components[i].types  == 'locality,political') {
        window.alert(results[0].address_components[i].long_name);
      };
  }

Upvotes: 0

Related Questions