In this post I will show how to create a map using Google Maps API V3 and the using browser geolocation we will add a marker to the user’s position. The finished product can be seen at http://ianluckraft.co.uk/demonstrations/google-maps-v3-and-geolocation.php
Let’s get started.
Create a basic HTML document
<!DOCTYPE html> <html> <head> <title>Google Maps V3 and Geolocation</title> </head> <body> </body> </html>
We need to add a div that will later contain our map. Between the opening and closing body tags place a div with an id of map.
<div id="map"></div>
We also need to do some basic styling of the div to give it a width and height. These values can easily be changed to suit your needs. In between the opening and closing head tags place a style block with the following style rules.
<style>
#map {
width:400px;
height:300px;
}
</style>
Now we need to start with our JavaScript. The first step is to load the Google APIs. This is done with a script tag and the source as follows.
<script src="http://www.google.com/jsapi"></script>
Now this is loaded we can move onto loading the maps scripts. Below our script tags for loading the Google APIs add opening and closing script tags. Between these script tags add the following.
google.load('maps', '3', {other_params:'sensor=true'});
This piece of JavaScript uses the now available google.load method. To load the map scripts we need to pass the load method three parameters.
- The API to load. In this case maps.
- The version of the API to use. In this case 3
- The maps API requires a other params to be passed with a sensor option set to true or false.
The sensor option tells the maps scripts if we will be detecting the user’s location. As we will be using the browser to detect the user’s location we set this to true.
The rest of our code will be between these script tags. Next we need to create a function to deal with the creation of the map and will also detect if the user agrees to having their location used. Place the following below the google.load call.
function mapInit() {
}
google.setOnLoadCallback(mapInit);
In addition to creating our mapInit function we use another Google method that will let us call a function when everything has been loaded. Using the Google method rather than a body.onload ensures that all of the Google API’s have been loaded before other functions are called.
We now create a variable containing our basic options for the map. These are
- A zoom value set to 0, the map will be as far zoomed out as possible
- The center position for the map using the maps LatLng function. We will set our map to 0 Latitude and 0 Longitude.
- The type of map to display. We will use a road map.
function mapInit() {
var myOptions = {
zoom: 0,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
}
Now we will actually create the map. Below our options add the following line.
map = new google.maps.Map(document.getElementById("map"), myOptions);
Here we are assigning a variable of map the value of a new Google Map. We also use the getElementById function to tell the maps script which element to add the map to. And lastly we pass in our options we previously declared.
If you refresh your browser you should now see a map taking up the space of our div with the id map.
Geolocation
Now we will deal with the user accepting or declining the use of their location.
The last part of our mapInit function will check if the browser supports geolocation. If it does then we call another function, if it doesn’t we are just using a simple alert to let us know. In a real application you would deal with this in a more elegant way. Add the following to the mapInit function.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(currentPositionCallback);
} else {
alert('The browser does not support geolocation');
}
Now we need to create the currentPositionCallback function. After our mapInit function add the following lines.
function currentPositionCallback(position) {
}
This is the function that will be called if the browser supports geolocation and the user agrees to share their location. It accepts a parameter of position that will contain the location information.
Next we will add a marker to the map where the user has been located. Add the following line to the currentPositionCallback function.
var user_lat_long = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
Here we create a new variable of user_lat_long that stores a maps LatLng, as we did when creating the map. We pass this the values from the position parameter of latitude and longitude. We will now use the user_lat_long variable to place a marker on the map.
var marker = new google.maps.Marker({
position: user_lat_long,
map: map
});
We have now created a variable to hold the new marker. We use the maps Marker function and pass in our user_lat_long for the position and also we need to tell the function which map to use, in our case it is our map variable.
To finish up we will set the center of the map to the user’s position and zoom into a more detailed level.
map.setCenter(user_lat_long); map.setZoom(15);
And here is the code in it’s entirety
<!DOCTYPE html>
<html>
<head>
<title>Google Maps V3 and Geolocation</title>
<!-- Set basic styling for the map div -->
<style>
#map {
width:400px;
height:300px;
}
</style>
<!-- Load the Google APIs -->
<script src="http://www.google.com/jsapi"></script>
<script>
// Load the map scripts
google.load('maps', '3', {other_params:'sensor=true'});
// Function to create a map and check for geolocation
function mapInit() {
// Set the options to be used when creating the map
var myOptions = {
zoom: 0,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the new
map = new google.maps.Map(document.getElementById("map"), myOptions);
// Check if the browser supports geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(currentPositionCallback);
} else {
alert('The browser does not support geolocation');
}
}
function currentPositionCallback(position) {
// Create a new latlng based on the latitude and longitude from the user's position
var user_lat_long = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Add a marker using the user_lat_long position
var marker = new google.maps.Marker({
position: user_lat_long,
map: map
});
// Set the center of the map to the user's position and zomm into a more detailed level
map.setCenter(user_lat_long);
map.setZoom(15);
}
google.setOnLoadCallback(mapInit);
</script>
</head>
<body>
<h1>Google Maps V3 and Geolocation</h1>
<div id="map"></div>
</body>
</html>


excuse me sir,
i’m developing website using google map api v3.
last 3 month i using geolocation feature, and it’s work
but today, i test my geolocation feature, it’s doesn’t work anymore,
i try using with many browser, such as chrome, firefox, IE9
could you try to test geolocation in your browser?
or only me have this problem in my computer
please reply in my email
thanks before
Do you have a URL that I can test for you?
Great Post. Thanks!!
Do you know how can I retrieve the zip code of the geolocation?
To get the zip code from latitude longitude values you will need to use reverse geocoding.
Using the example on this page if you add the following to the bottom of the currentPositionCallback function it will output the zip code / post code to the console
geocoder = new google.maps.Geocoder();
geocoder.geocode({‘latLng’: user_lat_long},
function(results, status) {
console.log(results[0].address_components[5].long_name);
});
This code creates a new geocoder and then passes it the latLng we already have for the users position.
The second parameter of the geocode function is a callback function and here it simply outputs the zip code.
There is lots of other information in the address_components object worth looking at.
Hope that helps you out.
Super! Thanks!!
Hello. Thank you for this tutorial. Was your web page designed for use with smartphones, both Android and iPhone or computer browsers? I currently have a google maps v3 site that I would like to develop for mobile devices, and would like it to place a marker at the user’s position. Thanks.
There is support for this technique on both iPhone and Android browsers. The main thing to keep in mind is that not all of the browsers / OS versions will have support or users may not have location services enabled.
My tip would be to ensure that you have good fallbacks for when users can not use the automatic location detection such as allowing them to choose their location.
That is so awesome and it works.
My question is now can you add an email address and send button to send to someone. I want to send a location along with a custom form to report invasive weed locations. Is this possible?
The first thing to do would be to get the lat long values and use those to construct a url for example
mysite.com/showmap/?lat=50.372&long=-4.1419
If you need some code to extract the lat long when a user clicks on the map let me know.
Then when someone visits your url you can grab the lat long values using server side or javascript then use them to display a marker on a map.
Does that help?
Ian,
This has helped me more than anything I have found on the web, but not entirely. When I try to include the filters from my fusion table with the code I get a syntax error.
To fix it I’ve had to leave out the initial location and elseif commands. (I really do not understand javascript.)
Would you mind telling me what I am doing wrong? I really had tried and tried. The website is at gfmap.com and my wonky implementation of your fine code is at gfmap.com/index2.html
The website is for people with gluten intolerance so we can tell each other about places that serve and sell gluten-free food.
Any help appreciated.
Thanks,
Matt
Hi Matt,
Thanks for the comment.
I’ve had a look on your site and the map zooms into my current location. There are no gluten free items near me but when I zoom out I can see pointers in France and Florida.
Have you solved this or is there other behaviour you are expecting.
Thanks
Ian
I think I’ve come a long way towards solving it (amazing how many hours I can waste on this stuff) but it is not working properly in Safari or IE. I think it would work if I can include your code for the non-geolocation-aware browsers, but I don’t know how to make it work without a syntax error.
For example, in Safari on a Mac and IE on PC I just get a grey box where the map should be. Then if I do a search on a place it works OK. I am presuming this is because the map does not know where its initial location should be.???
And thanks for your reply — really appreciate it.
Matt
Hi Matt,
Just checked in Safari and Mac and it does work. It’s not as quick to render the map as on Firefox or Chrome.
There is also a restaurant in my area now.
And yes, these things can eat up hours of your time easily.
Let me know how it’s going.
Thanks Ian! It was very informative, clear and to the point! I appreciate it and please continue your wonderful job.
Sincerely, Mehrdad
Thank you so much for this. The geolocation part doesn’t seem to be working for me though. I have put up an example on my website – is there something wrong with my code? I went through your tutorial line by line.
http://lizshannon.com/avis317/geolocation/test.html
If you could offer any help I’d really appreciate it. Thank you.
Thank you so much for this. The geolocation part doesn\’t seem to be working for me though. I have put up an example on my website – is there something wrong with my code? I went through your tutorial line by line.
http://lizshannon.com/avis317/geolocation/test.html
If you could offer any help I\’d really appreciate it. Thank you.
Ok I discovered the problem. In your breakdown of the coding you wrote:
var map = new google.maps.Map(document.getElementById(“map”), myOptions);
And the code in the entirety it is written as:
map = new google.maps.Map(document.getElementById(“map”), myOptions);
I was following the coding breakdown, instead of the whole code as one. I thought you might want to know so you can alter the tutorial.
Hi Liz,
Thanks for the comments and I’m glad you got it working.
I have changed the code example.
Thanks
Ian
Hi, Ian. First, this help big! So, awesome for the tutorial
I am currently developing an app mobile for android
Tried to test your geolocation, but it doesn’t seem to be as accurate as I test it on my PC browser
But my maps app (google maps) on android detect my location perfectly
do you know what the problem issue is?
Thanks
Hi Jonathan,
My initial thoughts are they may be using different methods to detect your location.
Looking at the Android documentation http://developer.android.com/guide/topics/location/strategies.html the GPS method of detecting location is not as accurate as using cell tower and WiFi.
They also mention varying accuracy under the “Challenges in Determining User Location” section.
My suggestion for apps using geolocation is to use detection as a helper for users but allow them to change the detected location to something they deem more accurate, e.g. by selecting a new point on the map.
I hope that helps you out.
Thanks
Ian
Hi Ian,
Please could you tell me where I can find a script for displaying google map for a particular postcode. For example, we are having a venue for the meeting with the postcode so we want people to see the map, like you get on the property website. Thanks. Nicki
Hi Nicki,
If you know the latitude and longitude of the location you can add a marker quite simply like I have on this example http://ianluckraft.co.uk/demonstrations/google-maps-with-marker.php
If you need to get the latitude and longitude from the post code you need to use reverse geocoding.
There are lots of good posts on that around that will be worth reading.
Thanks
Ian
Hey
i have taken this code off
https://google-developers.appspot.com/maps/documentation/javascript/examples/map-geolocation
and modifying it to suit my needs is the following code;
/**************************************************/
Google Maps JavaScript API v3 Example: Map Geolocation
var map;
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(‘map_canvas’),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: ‘Location found using HTML5.’
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn’t support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = ‘Error: The Geolocation service failed.’;
} else {
var content = ‘Error: Your browser doesn\’t support geolocation.’;
}
var options = {
map: map,
position: new google.maps.LatLng(19,72),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, ‘load’, initialize);
/****************************************/
on running the html code in the browser, i get the output as Error: Geolocation service failed, could you please tell me where am i going wrong?
Thank you
By just copying your code sample the first error I got was
google.maps is undefinedTo fix this I added this above the script tag
<script src="http://www.google.com/jsapi"></script>And then this within the script tag above var map;
google.load('maps', '3', {other_params:'sensor=true'});I then got another error about the google.maps.event.addDomListener(window, ‘load’, initialize); line
I switched this to
google.setOnLoadCallback(initialize);And everything then worked.
I hope that helps you out.
Great Job – Love your work!!!
I would like to input an address and get the lat. & long. info returned under the address input box after submitting the address – could you help with this please..?
Thank You Very Much
Vette.
Hello Vette,
That process is known as Geocoding. There are lots of good articles on the web about using Google Maps Geocoding. It’s probably best to have a look around for that. It would be a lot quicker than waiting for me to type up something.
Thanks
Ian
hi suppose i want to load in other users devices and also have multi mapmarkers at the same time, and watch as they move at the same time? how would i achieve this? i only know how to load my own latitude n longitude and used the watchposition to view my self as i move…. any help i get i would really appreciate and thank you
You would need to store all the information somewhere from each of the users, probably in a database. Then at intervals obtain the latest positions from the database and update the map accordingly.
The way you choose to implement this is really up to you and our preferred language.
You could use php / mysql / javascript or you could look at something like Meteor which is a bit newer and based at real time apps.
Hi Ian,
I’m coding a project using JSP and Google Maps v3 JavaScript API, and sometimes, when I do actions and redirect to map pages, I get a grey box, not the map, into “map_canvas”. If I search for an address or refresh the page it appears. Could be the error that the map loads before the geolocation coordinates are loaded?
Can you help me, please?
Thank you
Hi Carlos,
If you’re not already using it I’d suggest opening Chrome dev tools or Firebug in Firefox to see if there are any errors that are causing the grey box.
If not you could then try some debugging messages using console.log() to see when certain functions are being called. This would help you with your hunch that the map is not yet loaded before the coordinates.
Thanks
Ian
where using the comphrensive google map plugin for wordpress its not beeing updated for a long time.
its a good plugin showing a mix of all posts on a map. however it lacks the support for gps location. it would be nice to have it on our apps / browser using the users gps location.
can anybody have a look at it?
its not beeing updated for a long while.
I haven’t got the time at the moment but maybe someone else would like to take it up.
ok i tried bieng a script kiddie but im not good with js. i got a script setup for the plugin with geolocation options the page loads but it doesnt zoom in or show the marker. here is het the link if sombody would be kind to help us out:
http://pastebin.com/GvZDPFPT
i already screwed up the navigate to with this :$
Are you using Firebug or Chrome Developer tools?
If so do you get any errors there.
I’ve just tried your script with jQuery 1.9 and get the error “TypeError: $.browser is undefined”
You can see the solution to that error at http://stackoverflow.com/questions/14798403/typeerror-browser-is-undefined