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.

51 Responses to Google Maps V3 and Geolocation

  1. Eric says:

    Also wanted to add for those who are wondering about the marker:

    If you want to add the marker to the users location when the click to share it add this to your controller file


    $this->load->library('googlemaps');
    $config = array();
    $config['sensor'] = TRUE;

    $config['center'] = 'auto';

    //this is what adds the marker
    $config['oncenterchanged'] = 'if (!centreGot) {
    var mapCentre = map.getCenter();
    marker_0.setOptions({
    position: new google.maps.LatLng(mapCentre.lat(), mapCentre.lng())
    });
    }
    centreGot = true;';

    // Initialize the map
    $this->googlemaps->initialize($config);

    /* Create the Map || Will return the JS needed for the section and the HTML for the map where we want it to appear
    --- set up the marker ready for positioning
    --- once we know the users location */

    $marker = array();
    $this->googlemaps->add_marker($marker);
    $data['map'] = $this->googlemaps->create_map();

    //Loade the View(s)
    $this->load->view('welcome_message', $data);

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>