Last Updated: February 25, 2016
·
6.916K
· allthingssmitty

Implementing the Geolocation API with Google Maps API

Geolocation can be an added benefit to many web apps and using it with the Google Maps API is easy and fun.

First, obtain a Google Map API key and add it to your web page:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>

Now you're ready to start using the GoogleMap function to get your location (position):

// create Google map
function GoogleMap(position) {
  var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}

Once you've called the GoogleMap function, you can set ID, height, and width of the map. There are many map types, styles, and control options to customize your map.

Set up the map and marker using the google.maps.Map and google.maps.Marker functions:

// create Google map
function GoogleMap(position) {
  var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 20,
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var marker = new google.maps.Marker({
    map: map,
    position: location,
    animation: google.maps.Animation.DROP,
    title: "This is your location"
  });

  map.setCenter(location);
}

You can add a function to display an error if the location can't be retrieved from Google Maps:

// show error if location can't be found
function showError() {
  alert("Location can't be found");
}

Lastly, check if your browser supports geolocation and run the GoogleMap function:

// execute geolocation
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(GoogleMap, showError);
  } else {
  alert("Your browser does not support Geolocation.");
}

Happy coding.