Google Maps V3 and Geolocation

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.

  1. The API to load. In this case maps.
  2. The version of the API to use. In this case 3
  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>
This entry was posted in Web Development and tagged , . Bookmark the permalink.

46 Responses to Google Maps V3 and Geolocation

  1. hendra says:

    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

  2. ian says:

    Do you have a URL that I can test for you?

  3. Avi says:

    Great Post. Thanks!!
    Do you know how can I retrieve the zip code of the geolocation?

  4. ian says:

    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.

  5. Avi says:

    Super! Thanks!!

  6. Andrew says:

    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.

  7. ian says:

    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.

  8. Mark W says:

    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?

  9. ian says:

    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?

  10. Matt Martel says:

    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

  11. ian says:

    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

  12. Matt Martel says:

    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

  13. ian says:

    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.

  14. Mehrdad says:

    Thanks Ian! It was very informative, clear and to the point! I appreciate it and please continue your wonderful job.

    Sincerely, Mehrdad

  15. Liz says:

    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.

  16. Liz says:

    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.

  17. Liz says:

    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.

  18. ian says:

    Hi Liz,

    Thanks for the comments and I’m glad you got it working.

    I have changed the code example.

    Thanks

    Ian

  19. Jonathan says:

    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 :D

  20. ian says:

    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

  21. Dr Nicki says:

    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

  22. ian says:

    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

  23. Khushal says:

    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

  24. ian says:

    By just copying your code sample the first error I got was

    google.maps is undefined

    To 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.

  25. Vette Racer says:

    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.

  26. ian says:

    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

  27. jermaine says:

    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

  28. ian says:

    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.

  29. Carlos says:

    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

  30. ian says:

    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

  31. wva says:

    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.

  32. ian says:

    I haven’t got the time at the moment but maybe someone else would like to take it up.

  33. wva says:

    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

  34. wva says:

    i already screwed up the navigate to with this :$

  35. ian says:

    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

  36. jonathan says:

    For the people getting a grey box, I was having the same problem and just figured out that I was passing too much zoom into an area with no streets :/

  37. Stefano says:

    Hi man!
    there any tips to accept just the first time the agreement to share my position using the geolocation? i need to write my address in several moment during the day, and i can not click to proceed anytime

    Thanks

  38. ian says:

    Hi Stefano,

    My first thought is to store the data with local storage or a cookie.

    Then if there is nothing set use the browser to gather the data.

    My only concern there is I don’t know if there are any legal implications to storing data in that way.

  39. sanjay thakur says:

    hiiiiii…sir im using your code in my Samsung Phone model no gt6812 android versoin 4.1.2, bt when i run your code it ll display …only world map….doest show current postion….in google map v3 in gelocation bt i when run in browser it ll show my current positin when i allowed permission ….plz guide me thank in advance ………………

  40. ian says:

    Hi Sanjay,

    Whilst I’m not familiar with that phone and browse combination my suggestion would be to inspect the contents of the position variable in the function currentPositionCallback

    It sounds like there is not a lat long value being passed into the map.

    Thanks

    Ian

  41. renato says:

    Ian, your tutorial are clean and very helpfull.

    Im drawing the poligon on map, and next i need to get the coords lat lon of these points of polygon. Late i will send these points to database.

    Can you help me to make this ?

  42. ian says:

    Hi Renato,

    I’ve not actually used polygons with Google maps before.

    How are you placing the polygons on the map to begin with?

    Thanks

    Ian

  43. Hari Krishna says:

    Hi Ian,

    When trying to execute following GeoLocation Code, i want my mobile device to detect the my location automatically, but it does not. Please let me know, what changes i need to do in the code for this.

    function geoLocation()
    {
    if (! navigator.geolocation)
    {
    jAlert(‘Geolocation is not supported by your Mobile Device’);
    return;
    }

    // var options = { timeout: 31000, enableHighAccuracy: true, maximumAge: 90000 };
    var options = {enableHighAccuracy: true};
    navigator.geolocation.getCurrentPosition(function(position)
    {
    console.log (‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
    ‘Longitude: ‘ + position.coords.longitude + ‘\n’ +
    ‘Altitude: ‘ + position.coords.altitude + ‘\n’ +
    ‘Accuracy: ‘ + position.coords.accuracy + ‘\n’ +
    ‘Altitude Accuracy: ‘ + position.coords.altitudeAccuracy + ‘\n’ +
    ‘Heading: ‘ + position.coords.heading + ‘\n’ +
    ‘Speed: ‘ + position.coords.speed + ‘\n’ +
    ‘Timestamp: ‘ + new Date(position.timestamp) + ‘\n’);

    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    geocoder.geocode({‘latLng': latlng}, function(results, status)
    {
    if (status == google.maps.GeocoderStatus.OK)
    {
    $(‘#sourceId’).val(results[1].formatted_address);
    $(‘#destinationId’).val(results[1].formatted_address);
    }else
    {
    $.unblockUI();
    jAlert(‘Geocoder failed due to: ‘ + status);
    return;
    }
    });

    $.unblockUI();

    }, function (error)
    {
    $.unblockUI();
    var errorString = ”;

    if (error.code == 0)
    errorString = ‘Unknown error';
    else if (error.code == 1)
    errorString = ‘Access denied by user';
    else if (error.code == 2)
    errorString = ‘GPS Position unavailable';
    else if (error.code == 3)
    errorString = ‘Timed out';
    else
    errorString = error.message;

    jAlert(‘Unable to retrieve your location (Error Code: ‘ + error.code + ‘ , ‘ + ‘ Error Message: ‘ + errorString + ‘)’);
    return;
    }, options);
    }

    Regards

  44. Hari Krishna says:

    Hi Ian,

    I get a message always, google maps utility library v3 wants to use your location.
    Allow or Deny

    I want my code, to automatically detect the location, without any intervention

    Regards
    Hari Krishna

  45. ian says:

    Hi Hari,

    That is a browser security feature as some users may not want to always allow an application to know their location.

    Thanks

    Ian

  46. ian says:

    Hi,

    Without knowing the exact device you are using, and having access to it it is hard to know exactly where the code is failing.

    One thing to try is removing console.log functions. The JavaScript could be failing because you are using console.log and this is not a function available to the mobile browser.

    Thanks

    Ian

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>