Get location using HTML5’s geolocation API and Google Maps Javascript API

  1. Previous
  2. Next
  3. Recent

    1. Earn Money from Home: 25 Part-time Jobs for Housewives & Students
    2. 10 Simple Self-Defense Tips Indian Women Must Know
    3. How to Make Gravy For All Occasions
    4. 15 Ways to Use Waste Materials to Make Something Decorative and Useful
    5. Tips for Foreign Solo Travellers in India: 25 Things to Remember
    6. How to Tackle FOMO - The Fear of Missing Out!
    7. How to Increase the Taste of Food: 25 Tips to Make Delicious Recipes Yummier
    8. How to break yourself free from 'Dark Skin' mindset in color-conscious India
    9. How to Make Sandwich Dhokla at Home: A Tasty Indian Recipe
    10. How to Plan a Travel Itinerary: 7 Great Tips

If you’re building a website or app and require geographical location of users then you’re reading the right article as we’ll explain everything, right from detecting user geographical coordinates, to displaying location on Google Maps and getting postal address. Not just this, we’ll also tell a few tips on making your own GPS using the same idea. Its really simple, absolutely not a rocket science.

Before we move on to the tutorial part, here is a glimpse of what we’re making.

detect user location using geolocation api and google maps api

Here we’ll be using HTML5’s geolocation API and Google Maps Javascript API.

Geolocation API and Google Maps JS API

  1. Geolocation API of HTML5 retrieve user’s location coordinates – the latitude and longitude.
  2. Google Maps convert these coordinates to geographical location and display on map. Using Google Maps API, we can find a location, path between two destination, traffic information and lots more.

Example: If I’m at Mathura then Geolocation API would fetch the coordinates like 27.4925, 77.6736. These coordinates are then sent to Google Maps which shows up my location on map.

The Tutorial

1. Load Javascript API for Google Maps: Include the code in the head section of the app to load Google Maps JS API.

<script language='Javascript' src='https://maps.googleapis.com/maps/api/js?v=3.exp'></script>

2. Get location coordinates using Geolocation API

<body onload='getLocation()'>
	<div id='user_location_address' style='line-height:30px;width:100%;'></div>
	<div id='map_display_area' style='height: 75%; width: 100%;'></div>
</body>
function getLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(show_map, show_error);
	}
	else {
		alert('Geolocation not supported by the browser');
	}
}

On page load, getLocation() and subsequently the getCurrentPosition() function is called. Permission to get location is asked from user using a popup as shown in the image.

asking for permission for geolocation coordinates

If permission is given, show_map() is called and if denied, show_error() is called.

3. Displaying Location on Google Map

function show_map(position) {
	location_coordinates = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	mapOptions = {zoom:14,center:location_coordinates};
	location_on_map = new google.maps.Map(document.getElementById('map_display_area'), mapOptions);
}

function show_error(error) {
	if(error.code==1) {
		alert('User Denied');
	}
	if(error.code==2) {
		alert('Position unavailable');
	}
	if(error.code==3) {
		alert('Timeout');
	}
}

Here we’re doing 2 things,

1. Instantiating google.maps.latLng class to get object representing location coordinates.

2. Creating object of google.maps.map class. The constructor map() is provided 2 parameters – element where the map should appear – #map_display_area & configurations for the map – mapOptions.

That’s it. Put the code together and run, you’ll see the map showing your current position. This is just the basic part, we can do more using Maps API.

Advanced Features

1. Getting more accurate location

The function getCurrentPosition() has 3 optional arguments.

function getLocation() {
	navigator.geolocation.getCurrentPosition(show_map, show_error, {enableHighAccuracy:true, timeout:5000, maximumAge:10000});
}
  1. enableHighAccuracy takes boolean value. When its set true, location information is highly accurate but may take time to locate. Default value is false.
  2. timeout is the maximum amount of time browser wait for location results to show up after permission is given. Value 5000 means browser will wait for 5 seconds and if results aren’t fetched it’ll show the timeout error.
  3. maximumAge is the time for which location results would remain in the browser memory.

2. Add Marker over Position

Displaying location on map is good but putting a pointer over it is better. Here is how you can do this,

markerOptions = {position:location_coordinates,title:"You're here buddy",map:location_on_map}
marker = new google.maps.Marker(markerOptions);

Just put the code inside show_map() at the bottom and see a stylish red colored pointer over location.

3. Getting user postal address

Getting address from user location coordinates can be done using geocode() method of Geocoder class of Google Maps API.

For this, we create an object of the class and call function passing coordinates value as parameter. The return value will be an array of address in different formats like {‘Chandanvan, Mathura, India’, ‘Mathura, India’, ‘Mathura-281001, India’}. Pick any one format and display.

Here is the code,

function get_user_address() {
	geocoder = new google.maps.Geocoder();
	geocoder.geocode({'latLng':coordinates},function(results,status) {
	if( results == google.maps.GeocoderStatus.OK ) {
		if (results[1]) {
			document.getElementById('user_location_address').innerHTML=results[1].formatted_address;
		}
		else {
			document.getElementById('user_location_address').innerHTML="User address fetching failed because "+error;
		}
	}
	});
}

To include address info, put the get_user_address() inside the show_map() function in Step 3.

4. Update user location on map like GPS

To monitor user location and update on map like GPS devices do is easy with watchPosition() function of Geolocation API. The function works same as getCurrentPosition() which gets current coordinates for once only. watchposition() monitors the user device and regularly updates the coordinates which can be updated on map.

blog comments powered by Disqus