Google Marker : Icon is invisible [duplicate] - javascript

I've seen lots of other questions similar to this (here, here and here), but they all have accepted answers that don't solve my problem. The best solution I have found to the problem is the StyledMarker library, which does let you define custom colours for markers, but I can't get it to use the default marker (the one you get when you do a google maps search - with a dot in the middle), it just seems to provide markers with a letter in, or with a special icon.

You can dynamically request icon images from the Google charts api with the urls:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FE7569
Which looks like this: the image is 21x34 pixels and the pin tip is at position (10, 34)
And you'll also want a separate shadow image (so that it doesn't overlap nearby icons):
http://chart.apis.google.com/chart?chst=d_map_pin_shadow
Which looks like this: the image is 40x37 pixels and the pin tip is at position (12, 35)
When you construct your MarkerImages you need to set the size and anchor points accordingly:
var pinColor = "FE7569";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
You can then add the marker to your map with:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
icon: pinImage,
shadow: pinShadow
});
Simply replace "FE7569" with the color code you're after. Eg:
Credit due to Jack B Nimble for the inspiration ;)

If you use Google Maps API v3 you can use setIcon e.g.
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
Or as part of marker init:
marker = new google.maps.Marker({
icon: 'http://...'
});
Other colours:
Blue marker
Red marker
Purple marker
Yellow marker
Green marker
Use the following piece of code to update default markers with different colors.
(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)

Here is a nice solution using the Gooogle Maps API itself. No external service, no extra library. And it enables custom shapes and multiple colors and styles. The solution uses vectorial markers, which googlemaps api calls Symbols.
Besides the few and limited predefined symbols, you can craft any shape of any color by specifying an SVG path string (Spec).
To use it, instead of setting the 'icon' marker option to the image url, you set it to a dictionary containing the symbol options. As example, I managed to craft one symbol that is quite similar to the standard marker:
function pinSymbol(color) {
return {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
fillColor: color,
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 2,
scale: 1,
};
}
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(latitude, longitude),
icon: pinSymbol("#FFF"),
});
I you are careful to keep the shape key point at 0,0 you avoid having to define marker icon centering parameters. Another path example, the same marker without the dot:
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
And here you have a very simple and ugly coloured flag:
path: 'M 0,0 -1,-2 V -43 H 1 V -2 z M 1,-40 H 30 V -20 H 1 z',
You can also create the paths using a visual tool like Inkscape (GNU-GPL, multiplatform). Some useful hints:
Google API just accepts a single path, so you have to turn any other object (square, cercle...) into a path and join them as a single one. Both commands at the Path menu.
To move the path to the (0,0), go to the Path Edit mode (F2) select all
the control nodes and drag them. Moving the object with F1, won't change the path node coords.
To ensure the reference point is at (0,0), you can select it alone and edit the coords by hand on the top toolbar.
After saving the SVG file, which is an XML, open it with an editor, look for the svg:path element and copy the content of the 'd' attribute.

Well the closest thing I've been able to get with the StyledMarker is this.
The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.
From the class use example use "%E2%80%A2" as your text, as in:
var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});
You will need to modifiy StyledMarker.js to comment out the lines:
if (text_) {
text_ = text_.substr(0,2);
}
as this will trim the text string to 2 characters.
Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:
marker = new google.maps.Marker({
map:map,
position: latlng,
icon: new google.maps.MarkerImage(
'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
new google.maps.Size(24, 24),
new google.maps.Point(0, 0),
new google.maps.Point(0, 24)
)
});

I've extended vokimon's answer a bit, making it a bit more convenient for changing other properties as well.
function customIcon (opts) {
return Object.assign({
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
fillColor: '#34495e',
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 2,
scale: 1,
}, opts);
}
Usage:
marker.setIcon(customIcon({
fillColor: '#fff',
strokeColor: '#000'
}));
Or when defining a new marker:
const marker = new google.maps.Marker({
position: {
lat: ...,
lng: ...
},
icon: customIcon({
fillColor: '#2ecc71'
}),
map: map
});

Hi you can use icon as SVG and set colors. See this code
/*
* declare map and places as a global variable
*/
var map;
var places = [
['Place 1', "<h1>Title 1</h1>", -0.690542, -76.174856,"red"],
['Place 2', "<h1>Title 2</h1>", -5.028249, -57.659052,"blue"],
['Place 3', "<h1>Title 3</h1>", -0.028249, -77.757507,"green"],
['Place 4', "<h1>Title 4</h1>", -0.800101286, -76.78747820,"orange"],
['Place 5', "<h1>Title 5</h1>", -0.950198, -78.959302,"#FF33AA"]
];
/*
* use google maps api built-in mechanism to attach dom events
*/
google.maps.event.addDomListener(window, "load", function () {
/*
* create map
*/
var map = new google.maps.Map(document.getElementById("map_div"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
/*
* create infowindow (which will be used by markers)
*/
var infoWindow = new google.maps.InfoWindow();
/*
* create bounds (which will be used auto zoom map)
*/
var bounds = new google.maps.LatLngBounds();
/*
* marker creater function (acts as a closure for html parameter)
*/
function createMarker(options, html) {
var marker = new google.maps.Marker(options);
bounds.extend(options.position);
if (html) {
google.maps.event.addListener(marker, "click", function () {
infoWindow.setContent(html);
infoWindow.open(options.map, this);
map.setZoom(map.getZoom() + 1)
map.setCenter(marker.getPosition());
});
}
return marker;
}
/*
* add markers to map
*/
for (var i = 0; i < places.length; i++) {
var point = places[i];
createMarker({
position: new google.maps.LatLng(point[2], point[3]),
map: map,
icon: {
path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",
scale: 0.6,
strokeWeight: 0.2,
strokeColor: 'black',
strokeOpacity: 1,
fillColor: point[4],
fillOpacity: 0.85,
},
}, point[1]);
};
map.fitBounds(bounds);
});
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_div" style="height: 400px;"></div>

since version 3.11 of the google maps API, the Icon object replaces MarkerImage. Icon supports the same parameters as MarkerImage. I even found it to be a bit more straight forward.
An example could look like this:
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
for further information check this site

As others have mentioned, vokimon's answer is great but unfortunately Google Maps is a bit slow when there are many SymbolPath/SVG-based markers at once.
It looks like using a Data URI is much faster, approximately on par with PNGs.
Also, since it's a full SVG document, it's possible to use a proper filled circle for the dot. The path is modified so it is no longer offset to the top-left, so the anchor needs to be defined.
Here's a modified version that generates these markers:
var coloredMarkerDef = {
svg: [
'<svg viewBox="0 0 22 41" width="22px" height="41px" xmlns="http://www.w3.org/2000/svg">',
'<path d="M 11,41 c -2,-20 -10,-22 -10,-30 a 10,10 0 1 1 20,0 c 0,8 -8,10 -10,30 z" fill="{fillColor}" stroke="#ffffff" stroke-width="1.5"/>',
'<circle cx="11" cy="11" r="3"/>',
'</svg>'
].join(''),
anchor: {x: 11, y: 41},
size: {width: 22, height: 41}
};
var getColoredMarkerSvg = function(color) {
return coloredMarkerDef.svg.replace('{fillColor}', color);
};
var getColoredMarkerUri = function(color) {
return 'data:image/svg+xml,' + encodeURIComponent(getColoredMarkerSvg(color));
};
var getColoredMarkerIcon = function(color) {
return {
url: getColoredMarkerUri(color),
anchor: coloredMarkerDef.anchor,
size: coloredMarkerDef.size,
scaledSize: coloredMarkerDef.size
}
};
Usage:
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(latitude, longitude),
icon: getColoredMarkerIcon("#FFF")
});
The downside, much like a PNG image, is the whole rectangle is clickable. In theory it's not too difficult to trace the SVG path and generate a MarkerShape polygon.

In Internet Explorer, this solution does not work in ssl.
One can see the error in console as:
SEC7111: HTTPS security is compromised by this,
Workaround : As one of the user here suggested replace
chart.apis.google.com to chart.googleapis.com for the URL path to avoid SSL error.

You can use this code it works fine.
var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");<br>
var marker = new google.maps.Marker({
position: yourlatlong,
icon: pinImage,
map: map
});

Combine a symbol-based marker whose path draws the outline, with a '●' character for the center. You can substitute the dot with other text ('A', 'B', etc.) as desired.
This function returns options for a marker with the a given text (if any), text color, and fill color. It uses the text color for the outline.
function createSymbolMarkerOptions(text, textColor, fillColor) {
return {
icon: {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
fillColor: fillColor,
fillOpacity: 1,
strokeColor: textColor,
strokeWeight: 1.8,
labelOrigin: { x: 0, y: -30 }
},
label: {
text: text || '●',
color: textColor
}
};
}

I try two ways to create the custom google map marker, this run code used canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.
var marker;
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {
lat: 59.325,
lng: 18.070
}
});
var markerOption = {
latitude: 59.327,
longitude: 18.067,
color: "#" + "000",
text: "ha"
};
marker = createMarker(markerOption);
marker.setMap(map);
marker.addListener('click', changeColorAndText);
};
function changeColorAndText() {
var iconTmpObj = createSvgIcon( "#c00", "ok" );
marker.setOptions( {
icon: iconTmpObj
} );
};
function createMarker(options) {
//IE MarkerShape has problem
var markerObj = new google.maps.Marker({
icon: createSvgIcon(options.color, options.text),
position: {
lat: parseFloat(options.latitude),
lng: parseFloat(options.longitude)
},
draggable: false,
visible: true,
zIndex: 10,
shape: {
coords: CustomShapeCoords,
type: 'poly'
}
});
return markerObj;
};
function createSvgIcon(color, text) {
var div = $("<div></div>");
var svg = $(
'<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +
'<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +
'<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +
'<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +
'</svg>'
);
div.append(svg);
var dd = $("<canvas height='50px' width='50px'></cancas>");
var svgHtml = div[0].innerHTML;
//todo yao gai bu dui
canvg(dd[0], svgHtml);
var imgSrc = dd[0].toDataURL("image/png");
//"scaledSize" and "optimized: false" together seems did the tricky ---IE11 && viewBox influent IE scaledSize
//var svg = '<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'
// + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'
// + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'
// + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'
// + '</svg>';
//var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
var iconObj = {
size: new google.maps.Size(32, 43),
url: imgSrc,
scaledSize: new google.maps.Size(32, 43)
};
return iconObj;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Your Custom Marker </title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://canvg.github.io/canvg/canvg.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>

I tried for a long time to improve vokimon's drawn marker and make it more similar to Google Maps one (and pretty much succeeded). This is the code I got:
let circle=true;
path = 'M 0,0 C -0.7,-9 -3,-14 -5.5,-18.5 '+
'A 16,16 0 0,1 -11,-29 '+
'A 11,11 0 1,1 11,-29 '+
'A 16,16 0 0,1 5.5,-18.5 '+
'C 3,-14 0.7,-9 0,0 z '+
['', 'M -2,-28 '+
'a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0'][new Number(circle)];
I also scaled it by 0.8.

These are custom Circular markers
small_red:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiklEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NUlH5v9rF5f+ZoCAwHaig8B8oPhOmKC1NU/P//7Q0DByrqgpSGAtSdOCAry9WRXt9fECK9oIUPXwYFYVV0e2ICJCi20SbFAuyG5uiECUlkKIQmOPng3y30d0d7Lt1bm4w301jQAOgcNoIDad1yOEEAFm9fSv/VqtJAAAAAElFTkSuQmCC
small_yellow:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAi0lEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NijL7v3p1+v8zZ6rAdGCg4X+g+EyYorS0NNv////PxMCxsRYghbEgRQcOHCjGqmjv3kKQor0gRQ8fPmzHquj27WaQottEmxQLshubopAQI5CiEJjj54N8t3FjFth369ZlwHw3jQENgMJpIzSc1iGHEwB8p5qDBbsHtAAAAABJRU5ErkJggg==
small_green:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiElEQVR42mNgQIAoIF4NxGegdCCSHAMzEC81izL7n746/X/VmSowbRho+B8oPhOmKM02zfb/TCzQItYCpDAWpOhA8YFirIoK9xaCFO0FKXrY/rAdq6Lm280gRbeJNikWZDc2RUYhRiBFITDHzwf5LmtjFth3GesyYL6bxoAGQOG0ERpO65DDCQDX7ovT++K9KQAAAABJRU5ErkJggg==
small_blue:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAiklEQVR42mNgQIAoIF4NxGegdCCSHAMzEC81M4v6n56++n9V1RkwbWgY+B8oPhOmKM3WNu3/zJn/MbCFRSxIYSxI0YHi4gNYFRUW7gUp2gtS9LC9/SFWRc3Nt0GKbhNtUizIbmyKjIxCQIpCYI6fD/JdVtZGsO8yMtbBfDeNAQ2AwmkjNJzWIYcTAMk+i9OhipcQAAAAAElFTkSuQmCC
small_purple:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAi0lEQVR42mNgQIAoIF4NxGegdCCSHAMzEC+NMov6vzp99f8zVWfAdKBh4H+g+EyYorQ027T//2f+x8CxFrEghbEgRQcOFB/Aqmhv4V6Qor0gRQ8ftj/Equh2822QottEmxQLshubohCjEJCiEJjj54N8tzFrI9h36zLWwXw3jQENgMJpIzSc1iGHEwBt95qDejjnKAAAAABJRU5ErkJggg==
They are 9x9 png images.
Once they're on your page you can just drag them off and you'll have the actual png file.

change it to chart.googleapis.com for the path, otherwise SSL won't work

Using swift and Google Maps Api v3, this was the easiest way I was able to do it:
icon = GMSMarker.markerImageWithColor(UIColor.blackColor())
hope it helps someone.

Sometimes something really simple, can be answered complex. I am not saying that any of the above answers are incorrect, but I would just apply, that it can be done as simple as this:
I know this question is old, but if anyone just wants to change to pin or marker color, then check out the documentation: https://developers.google.com/maps/documentation/android-sdk/marker
when you add your marker simply set the icon-property:
GoogleMap gMap;
LatLng latLng;
....
// write your code...
....
gMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
There are 10 default colors to choose from. If that isn't enough (the simple solution) then I would probably go for the more complex given in the other answers, fulfilling a more complex need.
ps: I've written something similar in another answer and therefore I should refer to that answer, but the last time I did that, I was asked to post the answer since it was so short (as this one)..

You can use color code also.
const marker: Marker = this.map.addMarkerSync({
icon: '#008000',
animation: 'DROP',
position: {lat: 39.0492127, lng: -111.1435662},
map: this.map,
});

Related

Drawing svg circles with Google Maps

I'm working on a site that wants to use draw some circles to represent points of interest on a Google Map, but haven't found a way to draw a proper SVG circle element on the map.
The Google documentation outlines a circle element but these render as polygons rather than circles (take a look at the borders of the circle and you'll see they have a strange polygon fit to a rough circle shape, rather than a raw svg:circle element).
Is it possible to draw a true SVG circle with things like a r attribute for radius? Any pointers would be very helpful!
This feels a little janky but one can evidently freehand a circle in SVG then pass that drawn element as a marker to the map:
var icon = {
path: 'M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0',
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: 1
}
var marker = new google.maps.Marker({
position: {lat: 55, lng: 0},
map: map,
draggable: false,
icon: icon
});
via How to use SVG markers in Google Maps API v3
Very similar to the answer posted by duhaime, I have used this method before to get a circle by using
google.maps.SymbolPath.CIRCLE
in the path property (SymbolPath is just an enum for a couple of built-in shapes, CIRCLE equates to '0').
Not entirely sure of the rationale (assume the original size is effectively 2px wide), but you can use 'scale' like the radius, so a scale of 20 will give a diameter of 40px. If you add strokeWeight, this will add to the overall diameter by the stroke width. I think the formula for overall diameter might be (scale + round(0.5 * stoke)) * 2, because if you use an odd number for the stroke it ends up being the even number above.
In the example below, you will end up with circle diameter of 46px (even though the stroke is only 5)
var icon = {
path: google.maps.SymbolPath.CIRCLE,
fillColor: "#da291c",
fillOpacity: 0.5,
strokeColor: "blue",
strokeOpacity: 1,
strokeWeight: 5,
scale: 20
}
var marker = new google.maps.Marker({
position: {lat: 57, lng: -2},
map: map,
icon: icon
});

Add my own icon for google map instead of the default google map marker

When I add new event then it shows the location of that event on the google map and it is showing the google default marker but I have to change the default icon with mine own icon.
I want to add my own icon on the google map instead of the default google marker.how is this possible?
Very simply. You can specify any image URL for the marker's icon property, e.g. here I'm using an alternative one of Google's, but that could just as easily be a path to an image file on your own server:
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png",
map: map
});
This is very do able. You can use the Google Api to accomplish this. The maps api is not the easiest thing to use. I find with Google setting up the Api is the hard part. Once you get connected usually they document the code pretty well.
You can do it here,
This Link
// This example uses SVG path notation to add a vector-based symbol
// as the icon for a marker. The resulting icon is a star-shaped symbol
// with a pale yellow fill and a thick yellow border.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922}
});
var goldStar = {
path: 'M 125,5 155,90 245,90 175,145 200,230 125,180 50,230 75,145 5,90 95,90 z',
fillColor: 'yellow',
fillOpacity: 0.8,
scale: 1,
strokeColor: 'gold',
strokeWeight: 14
};
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: goldStar,
map: map
});
}

Google Maps API Markerclusterer Plus set icon

I'm making a google maps where the user can have an unlimited number of different categories on the map. I want to cluster each category in a differently colored cluster.
So far I'm using the google maps symbol for the individual markers, and I want to create a symbol for the marker clusters as well.
From checking the reference of the marker clusterer plus. I see that it asks for image url - is there any way to use symbols instead?
thanks!
A symbol(in the meaning of the maps-API), basically is defined by a SVG-path.
The MarkerClusterer draws the Cluster-Icons via <img/>.
A image-src may also be a data-URI, so it's possible to draw such an symbol(SVG-document) as <img/> .
Simple implementation:
function initialize() {
var Symbol=function(id,width,height,fill){
var s={
heart: {
p:'M340.8,83C307,83,276,98.8,256,124.8c-20-26-51-41.8-84.8-41.8C112.1,83,64,131.3,64,190.7c0,27.9,10.6,54.4,29.9,74.6 L245.1,418l10.9,11l10.9-11l148.3-149.8c21-20.3,32.8-47.9,32.8-77.5C448,131.3,399.9,83,340.8,83L340.8,83z',
v:'0 0 512 512'
},
gear: {
p:'M462,280.72v-49.44l-46.414-16.48c-3.903-15.098-9.922-29.343-17.675-42.447l0.063-0.064l21.168-44.473l-34.96-34.96 l-44.471,21.167l-0.064,0.064c-13.104-7.753-27.352-13.772-42.447-17.673L280.72,50h-49.44L214.8,96.415 c-15.096,3.9-29.343,9.919-42.447,17.675l-0.064-0.066l-44.473-21.167l-34.96,34.96l21.167,44.473l0.066,0.064 c-7.755,13.104-13.774,27.352-17.675,42.447L50,231.28v49.44l46.415,16.48c3.9,15.096,9.921,29.343,17.675,42.447l-0.066,0.064 l-21.167,44.471l34.96,34.96l44.473-21.168l0.064-0.063c13.104,7.753,27.352,13.771,42.447,17.675L231.28,462h49.44l16.48-46.414 c15.096-3.903,29.343-9.922,42.447-17.675l0.064,0.063l44.471,21.168l34.96-34.96l-21.168-44.471l-0.063-0.064 c7.753-13.104,13.771-27.352,17.675-42.447L462,280.72z M256,338.4c-45.509,0-82.4-36.892-82.4-82.4c0-45.509,36.891-82.4,82.4-82.4 c45.509,0,82.4,36.891,82.4,82.4C338.4,301.509,301.509,338.4,256,338.4z',
v:'0 0 512 512'
},
vader: {
p:'M 454.5779,419.82295 328.03631,394.69439 282.01503,515.21933 210.30518,407.97233 92.539234,460.65437 117.66778,334.11278 -2.8571457,288.09151 104.38984,216.38165 51.707798,98.615703 178.2494,123.74425 224.27067,3.2193247 295.98052,110.46631 413.74648,57.784277 388.61793,184.32587 509.14286,230.34714 401.89587,302.057 z',
v:'0 0 512 512'
}
}
return ('data:image/svg+xml;base64,'+window.btoa('<svg xmlns="http://www.w3.org/2000/svg" height="'+height+'" viewBox="0 0 512 512" width="'+width+'" ><g><path fill="'+fill+'" d="'+s[id].p+'" /></g></svg>'));
}
var center = new google.maps.LatLng(37.4419, -122.1419);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 1,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = [];
for (var i = 0; i < 500; i++) {
var dataPhoto = data.photos[i];
var latLng = new google.maps.LatLng(dataPhoto.latitude,
dataPhoto.longitude);
var marker = new google.maps.Marker({
position: latLng
});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers,{styles:[
{width:50,height:50,url:Symbol('heart',50,50,'red')},
{width:75,height:75,url:Symbol('gear',75,75,'green')},
{textColor:'tomato',textSize:'18',width:100,height:100,url:Symbol('vader',100,100,'blue')}
]});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,body,#map{height:100%;margin:0;padding:0;}
<div id="map"></div>
<script src="http://maps.googleapis.com/maps/api/js?v=3"></script>
<script src="https://cdn.rawgit.com/mahnunchik/markerclustererplus/master/src/data.json"></script>
<script src="https://cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>
The properties of the symbols are:
p (the path)
v (the viewBox)
Note: window.btoa is not supported by IE<10 , you'll need to implement it on your own when you need to support older IEs
In the past I had to deal with this.
To solve it what I did was to extend the class Cluster to add a new Google Marker as an attribute. This marker, attached at the same position as the cluster object, is the one that will show the symbol.
Remember that to avoid the overlap of your symbol and the cluster image you will have to set the opacity to 0 in the style of the clusters.
Hope it works for you.

Draw radius in meters using Maps API v3 Data layer based on GeoJSON

I am using the Maps API v3 and added a GeoJSON file to create a circle (based on google.maps.Symbol objects) around each entry in the GeoJSON-file -- which works quite fine by using the setStyle-functionality:
map.data.addGeoJson('url_to_GeoJSON');
..
map.data.setStyle(function(feature) {
return /** #type {google.maps.Data.StyleOptions} */({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: '#f00',
fillOpacity: 0.5,
strokeWeight: 0
}
});
});
Now I would need to draw a circle with a static radius in meters around each point, like it is provided by the regular google.maps.CircleOptions with its 'radius'.
Is there any possibility to use the very comfortable data layer 'addGeoJson'- and 'setStyle'-features in combination with a geographically correct radius in meters around each point?
I would be very happy to avoid setting up each marker manually "the old way" by iterating through the whole GeoJSON-file with
new google.maps.Circle({radius: 20000});
Any help is greatly appreciated! Thanks in advance!
After adding the code of Dr. Molle, there seems to be an issue while using multiple google.maps.Data-Objects, that should be shown/hide by checking/unchecking a checkbox within the website. This is my actual code, which already shows the data layer with drawn circles, but does not hide the circles of the specific data layer when unchecking a checkbox:
var map;
var dataset1 = new google.maps.Data();
var dataset2 = new google.maps.Data();
var dataset3 = new google.maps.Data();
function initialize() {
// Create a new map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 6,
center: {lat: 50.678240, lng: 9.437256},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
checkDataset();
}
function checkDataset() {
if (document.getElementById('chkDataset1').checked) {
// Define styles for dataPlug9 and apply to map-object.
dataset1.setStyle(function(feature) {
var geo = feature.getGeometry();
// Check for a point feature.
if(geo.getType().toLowerCase()==='point'){
//create a circle
feature.circle = new google.maps.Circle({
map: map,
center: geo.get(),
radius: 200000,
fillColor: '#FF0000',
fillOpacity: 0.05,
strokeColor: '#FF0000',
strokeOpacity: 0.4,
strokeWeight: 1
});
//trigger the dblclick-event of map.data on a dblclick on the circle
google.maps.event.addListener(feature.circle, 'dblclick',function(e){
e.stop();
google.maps.event.trigger(this.getMap().data,'dblclick', {feature:feature})
});
// Hide the marker-icon.
return {visible:false};
}});
// Remove feature on dblclick.
google.maps.event.addListener(dataset1,'dblclick',function(f){
this.remove(f.feature);
});
// Remove circle too when feature will be removed.
google.maps.event.addListener(dataset1,'removefeature',function(f){
try{f.feature.circle.setMap(null);}catch(e){}
});
dataset1.loadGeoJson('data/plug1.json');
dataset1.setMap(map);
} else {
dataset1.removefeature();
// This doesn't work either ..
dataset1.setMap(null);
}
}
I also added the above routine of function checkDataset() for the other 2 datasets (dataset2 and dataset3) and changed 'dataset1' to 'dataset2 / dataset3'.
You don't need to iterate "manually", setStyle already iterates over the features.
You may use it to execute additional code(e.g. create a google.maps.Circle):
map.data.setStyle(function(feature) {
var geo= feature.getGeometry();
//when it's a point
if(geo.getType().toLowerCase()==='point'){
//create a circle
feature.circle=new google.maps.Circle({map:map,
center: geo.get(),
radius: 20000,
fillColor: '#f00',
fillOpacity: 0.5,
strokeWeight: 0});
//and hide the marker when you want to
return {visible:false};
}});
Edit:
related to the comment:
The circles will be saved as a circle-property of the features(note: this property is not a property in the meaning of geoJSON, so it may not be accessed via getProperty).
You may add a listener for the removefeature-event and remove the circle there, so the circle will be removed when you remove the feature.
Sample code that will remove a feature(including the circle) on dblclick:
map.data.setStyle(function(feature) {
var geo= feature.getGeometry();
//when it's a point
if(geo.getType().toLowerCase()==='point'){
//create a circle
feature.circle=new google.maps.Circle({map:map,
center:geo.get(),
radius:200000,
fillColor: '#f00',
fillOpacity: 0.5,
strokeWeight: 0});
//trigger the dblclick-event of map.data on a dblclick on the circle
google.maps.event.addListener(feature.circle, 'dblclick',function(e){
e.stop();
google.maps.event.trigger(this.getMap().data,'dblclick',{feature:feature})
});
//and hide the marker
return {visible:false};
}});
//remove the feature on dblclick
google.maps.event.addListener(map.data,'dblclick',function(f){
this.remove(f.feature);
});
//remove the circle too when the feature will be removed
google.maps.event.addListener(map.data,'removefeature',function(f){
try{f.feature.circle.setMap(null);}catch(e){}
});

Google Maps: Polygon and Marker Z-Index

I have a Google Map with many markers (yellow circles), and I implemented a tool to draw polygons over the markers. However, the polygon is behind the markers while drawing (and stays behind when complete).
I tried changing the ZIndex in both markers and polygons, but it seems to alter the way in which markers are shown with respect to other markers, and not with respect to polygons. I also tried
polygon.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
How can I bring the polygon to the front?
This won't solve the problem, but it will explain why the things you tried didn't work.
The Maps API uses several layers known as MapPanes in a fixed Z order:
4: floatPane (infowindow)
3: overlayMouseTarget (mouse events)
2: markerLayer (marker images)
1: overlayLayer (polygons, polylines, ground overlays, tile layer overlays)
0: mapPane (lowest pane above the map tiles)
So the marker images in layer 2 are always above the polygons in layer 1. When you fiddle with the z-index on the markers, you're just adjusting them relative to each other. That doesn't do any good, because they are all in a layer above the polygons.
What can you do about this? The only solution I can think of is to create your own OverlayView for the polygons or the markers so you can put them in the MapPane you want.
Are your markers clickable, or are they just static images? If they aren't clickable, you could possibly get away with drawing them yourself in the mapPane. Then your polygons would be above them. Or the opposite: you could draw the polygons yourself in one of the higher layers, maybe in floatShadow.
The problem then is you have to do all of your own drawing, either with a canvas element or with DOM images. And your own mouse hit testing too if they are clickable.
There aren't a lot of good OverlayView examples out there, but I'll mention one of my own: a little library I wrote a while ago called PolyGonzo, where the polygonzo.js file has the OverlayView implementation. The code isn't great - I threw it together in too much of a hurry - but it may help give you some ideas.
I know this question is old but for future users I wanna share my approach:
Shapes with higher zIndex values displaying in front of those with lower values. For this example I am using Polygon but is similar for other shapes:
var globalZIndex = 1; //Be sure you can access anywhere
//... Other instructions for creating map, polygon and any else
polygon.setOptions({ zIndex: globalZIndex++ });
Notice that markers have a method setZIndex(zIndex:number).
I found this solution
To Create a Symbol use this code below
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: '#181727',
fillColor: '#50040B',
};
var dashedSymbol = {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 4
};
[![function MakeMarker(pinColor){
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
return pinImage;
}][1]][1]
FlowMarkersdashed(new google.maps.LatLng(positionorigin[0], positionorigin[1]),
new google.maps.LatLng(positiondestination[0], positiondestination[1]), myObject[i]['flowfluxphysique'][j]['colorFlux'], dashedSymbol, j);
function FlowMarkersdashed(latlngOrgin, latlngDest, ColorFlow, Symbol, indexvar){
var flightPlanCoordinates = [
latlngOrgin,
{lat: latlngOrgin.lat() + (indexvar) * 2, lng: latlngOrgin.lng()},
// {lat: -18.142, lng: 178.431},
latlngDest,
];
var line = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeOpacity: 0,
icons: [{
icon: Symbol,
// offset: '100%',
offset: '0',
repeat: '20px'
// repeat: '20px'
}],
strokeColor: "#"+ColorFlow,
geodesic: true,
// editable: true,
map: map
});
}
And to Create a Flow Marker try this code
FlowMarkers(new google.maps.LatLng(positionorigin[0], positionorigin[1]),
new google.maps.LatLng(positiondestination[0], positiondestination[1]), myObject[i]['flowfluxinformation'][j]['colorFlux'], lineSymbol,j);
function FlowMarkersdashed(latlngOrgin, latlngDest, ColorFlow, Symbol, indexvar){
var flightPlanCoordinates = [
latlngOrgin,
{lat: latlngOrgin.lat() + (indexvar) * 2, lng: latlngOrgin.lng()},
// {lat: -18.142, lng: 178.431},
latlngDest,
];
var line = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeOpacity: 0,
icons: [{
icon: Symbol,
// offset: '100%',
offset: '0',
repeat: '20px'
// repeat: '20px'
}],
strokeColor: "#"+ColorFlow,
geodesic: true,
// editable: true,
map: map
});
}
This is my result
Change this method call:
polygon.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
to this:
polygon.setZIndex(4);

Categories