Fetching current location address using GeoLocation and Google Map

Fetching current location address using GeoLocation and Google Map

HTML Geolocation API is used to fetch geographical position of a user. It can be possible only the user approves it. Geolocation is more accurate for the GPS Enabled mobile devices and others less accuracy. In this post how retrieve the address using Geolocation and Google Map API.

HTML

<html>
<body>
<input type='button' value='Find Address' onclick="getLocation();">
<div id="address">  </div> 
<div id="map_canvas" valign='top' style="width:500px; height:450px;"></div>
</body>
</html>

 

External Resources

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>

JavaScript

<script type="text/javascript"> 

var map;
var infowindow;
google.maps.event.addDomListener(window, "load", function () {

var latlng = new google.maps.LatLng(34,-117.5);
map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 8,
  center: latlng, 
  zoomControl: true,
  scaleControl: true, 
  mapTypeId: google.maps.MapTypeId.ROADMAP
}); 
infoWindow = new google.maps.InfoWindow(); 
});


function getLocation() {
var options = {
  enableHighAccuracy: true,
  timeout: 30000,
  maximumAge: 300
};
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(showPosition,errorPostion,options );
}  
}
function showPosition(position) { 
    var lat=position.coords.latitude;
    var lng=position.coords.longitude; 
    var point = new google.maps.LatLng(lat, lng);
    map.panTo(point);
    findAddress(point);
} 
function errorPostion(error) { 
     switch(error.code) {
        case error.PERMISSION_DENIED:
            errorMessage = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            errorMessage = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            errorMessage = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            errorMessage = "An unknown error occurred."
            break;
    }
    alert("Error : " + errorMessage);
}
 
function findAddress(point) {
var geocoder = new google.maps.Geocoder();
    geocoder.geocode({latLng: point}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                document.getElementById('address').innerHTML=results[0].formatted_address;
                infoWindow.setContent(results[0].formatted_address);
                infoWindow.setPosition(point);
                infoWindow.open(map);
            }
        }
    });
} 
</script>

 

Call getLocation() function by click on  ‘Find Address’ button  and checks the browser supports GeoLocation API using navigator.geolocation object, if yes then call navigator.geolocation.getCurrentPosition() with showPosition() as a call back function if the location lookup was successful. The browser calls showPosition() function with current location using position object, which has longitude and latitude as properties.

Using Google MAP API to get address from the longitude and latitude values, for that we call getAddressFromLatLang function. Inside the findAddress() function, I’ve create an object of google.maps.Geocoder and calling its geocode() method with latitude and longitude and it returns array of addresses for that location.

 

Leave a Reply

Top