Google Maps API – How to make a custom marker

What’s up guys, Eze is here. Today I want to show you how easy is to create a custom marker using the Google Maps API. First let’s create a map reference using the Google Maps API. We will be using this object to place our marker.

// Create a map centered in NY
vm.map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7128 , lng: 74.0059},
zoom: 15
});

As you can see in our code above we only need to pass as a parameter the element reference, in my case it’s just a div element with id = ‘map’. The API will create the map view in this element. Then using the PlacesService we get the details of an specific place. I’m using this service because in my working example (you can check the code here) I have an input element where the user can select a place, this input is populated using the autocomplete service so basically I have the place_id parameter to provide but if you don’t want to use it in this way in the request object you can provide a reference property to search different places.

 

var request = {
placeId: place.placeId
};

var service = new google.maps.places.PlacesService(vm.map);
service.getDetails(request, callback);

function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: vm.map,
position: results.geometry.location,
title: results.formatted_address
});
var infowindow = new google.maps.InfoWindow();
vm.map.setCenter({lat: results.geometry.location.lat(), lng: results.geometry.location.lng()})
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('
<div><img src="'+ vm.place.photoUrl + '" style="width:128px;height:128px;"/></div>
');
infowindow.open(vm.map, this);
});
}

Once I get the details for a specific place I use the Marker object to create a new marker in the map. The object I’m using to create this instance contains the reference to my map, the geometry location object which I get from PlacesService and a title. And that’s it, this is all you need to create a new marker in a map using the Javascript library for Google Maps API.

places.PNG

For a complete reference of Google Maps API use this link

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s