Geolocation with JavaScript and Google Maps

- Andrés Cruz

En español

Geolocation with JavaScript and Google Maps

Google Maps is an excellent tool for viewing scrollable maps and even routes between different points; this excellent tool is available to use in our web projects. In this entry we will see how to use Google Maps in our web projects:

1

Obtaining the user's location, a topic already explained in the last article Geolocation with JavaScript:

myLatlng = {
	Lat: position.coords.latitude,
	Lng: position.coords.longitude
}

2

We include a link to the Google Maps API in our HTML document to be able to use it:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

3

Then we include the canvas where the map will be drawn:

<div id="map_canvas" style="width:500px; height:500px"></div>

Note that the map can be of different sizes; For the purposes of this example it will be 500px X 500px.

4

The penultimate step is to build the object used to manipulate the map options:

var mapOptions = {
  zoom: 8,
  center: new google.maps.LatLng(myLatlng.Lat, myLatlng.Lng),
  mapTypeId: google.maps.MapTypeId.ROADMAP
};

Types of maps that are available in the Google Maps API:

  • MapTypeId.ROADMAP displays the default road map view.
  • MapTypeId.SATELLITE displays satellite images from Google Earth.
  • MapTypeId.HYBRID displays a mix of normal and satellite views.
  • MapTypeId.TERRAIN displays a physical map based on relief information.

Possible zoom levels range from 0 to 21 for the farthest.

5

The last step is to build the map:

var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

Building our basic map

1+2+3+4+5

Now let's look at all the steps together:

 

Conclusion

Here we can see an extension of our last article: Geolocation with JavaScript using the same bases explained; but this time using the Google Maps API to show the user's location.

I agree to receive announcements of interest about this Blog.

Using the Google Maps API to display the user's location.

- Andrés Cruz

En español