Google Maps LogoMuch as with the map, creating a marker is done by instantiating the Marker() constructor.

In Part I of this article, we learned how to show a Google Map in a web page, using the Google Maps API. Now in this article, we’ll learn how to add a marker to the map. In Part I we created a function named “successHandler” which was passed as a callback to the getCurrentPosition() method of the navigator’s geolocation object. And inside of this function, we instantiated the Map() constructor of the google.maps object.

Example # 1

In Example # 1, we have the code that adds a marker to the map. When instantiating the Marker() constructor, we pass it an object literal, which then provides settings that the marker needs in order to display properly. The “map” property references the “map” variable that was created earlier in the scope of the “successHandler” function. Once again, we instantiate the LatLng() constructor, providing the user’s latitude and longitude values. Now the “title” property is a string and can be anything you like. It is the text that users will see when they mouse over the marker.

Example # 2

In Example # 2, we have the full-page markup for our working demo. This example builds upon the demo from Part I. So the code is virtually identical, except for instantiation of the Marker() constructor.

Here is the JsFiddle.net link for this article’s working demo: http://jsfiddle.net/uQ35v/1/

Summary

In this article we learned how to place a marker on a Google Map. In doing so, we learned that just as in the case with the map, we instantiate the Marker() constructor. We discussed how settings are passed into the constructor by using an object literal, and how to set the text that is displayed in the marker on mouse-over.

Helpful Links for adding a marker to a Google Map

https://developers.google.com/maps/documentation/javascript/examples/marker-simple

One Comment

Comments are closed.