Geocoding an address

40 views
Skip to first unread message

Marcelo A. Robin

unread,
Jun 25, 2017, 7:34:20 PM6/25/17
to Google Maps JavaScript API v3
Hello everyone: I have a simple text field and a button. In the text field the user can enter an address and when I press the button, what I do is geocode the address to get the geographical coordinates. To get them I do the following:

<? Php


If ($ _POST) {
$
Url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=";
$
Address = $ _POST ['address'];
$
Call = $ url.urlencode ($ address);
$
Response = json_decode (file_get_contents ($ call), true);


If ($ response ['status']! = 'OK') {
     
Echo "It was not possible to geocode the address. Please re-enter the data.";
     
Exit;
}


}




?>


Now, I know that in the response variable I have the coordinates, but I do not know how to display them, how to get them ... Can you give me a hand?

PS: I tried to put a variable "$ length" and I made a "count ($ response)" and it returned a "2" that is, there are the coordinates but I do not know how to recover them !!!

Ema Colombo

unread,
Jun 27, 2017, 7:27:31 PM6/27/17
to Google Maps JavaScript API v3
This is what I did for my syte. I'm working on MVC, but maybe I'll help you.

<script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: { lat: 38.897725, lng: -77.032421 } }); var geocoder = new google.maps.Geocoder(); document.getElementById('submit').addEventListener('click', function () { geocodeAddress(geocoder, map); }); } function geocodeAddress(geocoder, resultsMap) { var address = document.getElementById('address').value; geocoder.geocode({ 'address': address }, function (results, status) { if (status === 'OK') { resultsMap.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: resultsMap, position: results[0].geometry.location }); $('#CityName').val(results[0].address_components[0].long_name); $('#lat').val(results[0].geometry.location.lat); $('#lng').val(results[0].geometry.location.lng); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } </script>


When the user clicks on search button the GeocodeAddress function is executed.
Reply all
Reply to author
Forward
0 new messages