lang="en-US"> Google Maps Tutorial: You Are Here in 3 Easy Steps –  Design1online.com, LLC

Google Maps Tutorial: You Are Here in 3 Easy Steps

Google Maps

I’ve been playing with Google maps lately and I thought I would share this little tidbit. It still needs some refinement (ie fetching your location from IP for non-html5 compliant browsers and letting you set your location) but it may give you the start you were looking for.

1. Create a Google maps API key

You can find the instructions on the Google maps Getting Started documentation. Basically you need to generate the key for the website that will be hosting this code so that Google will honor the API request.

2. Create a HTML File



  
    
    
    You Are Here
    
    
        
  
  
    

3. Create a Javascript File

I called mine javascript.js. If you change the name you’ll need to update it in your .html file above.

/**
* Purpose: ask the browser for the user's location (html5)
* Preconditions: html5 is enabled on the browser
* Postconditions: map initialized with user's position if browser is html5 enabled and position given
**/
function getLocation()
{
    if (navigator.geolocation)
        navigator.geolocation.getCurrentPosition(initMap);
    else
        alert("Geolocation is not supported by this browser.");
}

/**
* Purpose: start the google map
* Preconditions: position object
* Postconditions: map centered around the user's position with a zoom of 15
**/
function initMap(position) {

    console.log('Your position is:', position.coords.latitude, position.coords.longitude);
    
  var mapOptions = {
    zoom: 15,
    center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
 
    setMarker(map, position, "You!", "You Are Here");
}

/**
* Purpose: set a marker on a map
* Preconditions: map reference, position, title of the marker window, message in the marker window
* Postconditions: marker event listener added to the map
**/
function setMarker(map, position, title, message) {

     var marker = new google.maps.Marker({
      position: position,
      map: map
    });
        
  marker.setTitle(title);
        
  var infowindow = new google.maps.InfoWindow({
    content: message
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(marker.get('map'), marker);
  });
}

google.maps.event.addDomListener(window, 'load', getLocation);

Demo Working Code

Want to see what it does? Fork this plunker to try it out and see the code. Remember you have to be using a HTML5 compliant browser and give it permission to view your location.

You may also like...

Leave a Reply