These days with web apps being run on tablets and smartphones, location-awareness is becoming of a preferable feature to have. Instead of an app asking the user to enter his location, the app finds it on its own.
The most reliable way of finding a user’s location in terms of latitude/longitude was using the Google Geolocation API, which was part of Google Gears. which unfortunately has been discontinued some months back.
However, geolocation still works if you are using Google Maps. And again it is NOT necessary to have to display a google map just because you want to do a geolocation call.
We are just using Google Maps to use its geolocation features.
The sample javascript is below:
<script src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function doLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var fld = document.getElementById("address");
if (fld) {
fld.value = "(" + latitude + "," + longitude + ")";
}
var coords = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById("mp"), mapOptions
);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
The front end script shown below:
<style type="text/css">
#mp {
height: 0px;
width: 0px;
}
</style>
<div id="mp"></div>
- In the javascript function, it is assumed there is a textbox called ‘address’, which will be assigned the lat/long value obtained from the geolocation call. Once you have the coordinates, you can assign it to anything you want.
- The div which will hold the google map has been given a width and height of zero, so it does not show. If you need a map then you can give it height and width and position.
- The function doLocation can be called at page load or on some click event in the page.




