1

I have this code that I use to populate two text inputs on a form for Latitude and Longitude. I was wondering if there is a way to retrieve the City, Street, and Zip Code also so I can use those to populate into the form as well?

google.maps.event.addListener(marker, 'dragend', function(marker){
  var latLng = marker.latLng;
  $latitude.value = latLng.lat();
  $longitude.value = latLng.lng();
});

Example:

$zipcode.value = latLng.postal_code();
$street.value = latLng.street_address();
$city.value = latLng.city();

Here is my full code:

function selectState(state_id){
 if(state_id!="-1"){
loadData('city',state_id);
var e = document.getElementById("state");
var stateloc = e.options[e.selectedIndex].value;

var address = state_id + stateloc;

var $latitude = document.getElementById('latitude');
var $longitude = document.getElementById('longitude');
var latitude = 73.00636021320537;
var longitude = -23.46687316894531;

var zoom = 10;
geocoder = new google.maps.Geocoder();
var LatLng = new google.maps.LatLng(latitude, longitude);

var mapOptions = {
  zoom: zoom,
  center: LatLng,
  panControl: false,
  zoomControl: true,
  scaleControl: true,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}  

var map = new google.maps.Map(document.getElementById('map'),mapOptions);



if (geocoder) {
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      map.setCenter(results[0].geometry.location);




var marker = new google.maps.Marker({
  position: results[0].geometry.location,
  map: map,
  title: 'Drag Me!',
  draggable: true
});

google.maps.event.addListener(marker, 'dragend', function(marker){
  var latLng = marker.latLng;
  $latitude.value = latLng.lat();
  $longitude.value = latLng.lng();
});



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

 });
}


  }else{$("#city_dropdown").html("<option value='-1'>Select city</option>");
  }
}
Jake H.
  • 563
  • 2
  • 11
  • 23
  • It is called "reverse geocoding". You can find everything you need at https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding – Floris Mar 03 '14 at 04:44
  • possible duplicate of [How to get address location from latitude and longitude in Google Map.?](http://stackoverflow.com/questions/19511597/how-to-get-address-location-from-latitude-and-longitude-in-google-map) – Ashoka Mondal Mar 03 '14 at 04:45
  • possible duplicate of [How to get the formated address from a dragged marker in Google Version Maps](http://stackoverflow.com/questions/12828044/how-to-get-the-formated-address-from-a-dragged-marker-in-google-version-maps) – geocodezip Mar 03 '14 at 05:11
  • You mean the functions you made up? `$zipcode.value = latLng.postal_code();`, those won't work. You need to call the reverse geocoder (as @Floris indicated in his comment), then parse out the fields you want. – geocodezip Mar 03 '14 at 05:29
  • They are working for the Latitude and Longitude. Am I not calling the reverse geocoder already? – Jake H. Mar 03 '14 at 05:45

1 Answers1

0

The problem you are facing is solved most simply by making a call to the reverse geocoder, which is at

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false

A very simple php script could look like this:

<?php
  $value=json_decode(file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false"));
  echo $value->results[0]->formatted_address;
?>

This produces the output

277 Bedford Avenue, Brooklyn, NY 11211, USA

I suggest (in line with your user name) that you start by "keeping it simple" - strip all the code from your page except the one that takes a Lon/Lat input, and calls the above. Prove to yourself that you can recreate this output (besides the formatted address, there are individual fields for number, street, etc - see the full structure returned). Then add further complexity (maps, pins, pulldowns, ...).

Using the example you had above,

var latitude = 73.00636021320537;
var longitude = -23.46687316894531;

the address returned is

Greenland

I guess that's what happens when you stick a pin in the middle of the wilderness:

enter image description here

UPDATE if you want to do this using only Javascript, you would be well advised to use jQuery to get the JSON parsing capability. Example script (loads same address as original example once page is loaded - the key things are the httpGet function which you could replace with an AJAX call, and the jQuery.parseJSON() call which helps turn the response into something from which you can extract useful information:

<html>
<script src='./js/jquery-1.11.0.min.js'></script>
<script>
function ready()
{
  var r = httpGet("https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false");
  document.write(getAddress(r));
}

function httpGet(theUrl)
{
    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

function getAddress(response)
{
  var obj = jQuery.parseJSON(response);
  return obj.results[0].formatted_address;
}

</script>
<body onload="ready()">
</body>
</html>

See this at work at http://www.floris.us/SO/geocode.html

Floris
  • 45,857
  • 6
  • 70
  • 122
  • Can I use php within javascript? Take a look at the links I posted < href="http://stackoverflow.com/questions/22148193/using-reverse-geocode-within-a-draggable-marker" here as well. – Jake H. Mar 03 '14 at 13:59
  • @KeepinItSimple - yes you could call php from within javascript; but you can also do a "pure JS" solution, see updated answer. – Floris Mar 03 '14 at 14:31