Google Maps Api And Custom Markers
I am using the google maps api and want to create some custom markers, they are all the same apart from the color, I don't want to repeat code like so // Add a custom marker var m
Solution 1:
One option would be to use a function to generate the icon (i.e. a createIcon
function), which takes the color as an argument and returns the icon anonymous object:
function createIcon(color) {
return {
path: 'M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z',
fillColor: color,
fillOpacity: 0.95,
scale: 2,
strokeColor: '#fff',
strokeWeight: 3,
anchor: new google.maps.Point(12, 24)
};
}
Then use that when you create the markers:
var marker1 = new google.maps.Marker({
map: map,
position: {
lat: 37.448,
lng: -122.143
},
icon: createIcon('#ff61b4')
});
code snippet:
function createIcon(color) {
return {
path: 'M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z',
fillColor: color,
fillOpacity: 0.95,
scale: 2,
strokeColor: '#fff',
strokeWeight: 3,
anchor: new google.maps.Point(12, 24)
};
}
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: createIcon('blue')
});
var marker1 = new google.maps.Marker({
map: map,
position: {
lat: 37.448,
lng: -122.143
},
icon: createIcon('#ff61b4')
})
var marker2 = new google.maps.Marker({
map: map,
position: {
lat: 37.44,
lng: -122.148
},
icon: createIcon('#05950a')
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
Solution 2:
You can use setOptions, eg: for changing only the icon
marker.setOptions({
icon = "http://labs.google.com/ridefinder/images/mm_20_white.png"
});
or clickable
marker.setOptions({clickable:false});
so you can do the same for all the marker options
Post a Comment for "Google Maps Api And Custom Markers"