Google Maps API 3 - Custom marker color for defaul

2019-01-03 19:27发布

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.

15条回答
祖国的老花朵
2楼-- · 2019-01-03 19:33

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

查看更多
Viruses.
3楼-- · 2019-01-03 19:36

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)
  )
});
查看更多
祖国的老花朵
4楼-- · 2019-01-03 19:37

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
});
查看更多
放荡不羁爱自由
5楼-- · 2019-01-03 19:37

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
6楼-- · 2019-01-03 19:38

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>

查看更多
我想做一个坏孩纸
7楼-- · 2019-01-03 19:39

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"),
});

Vector Marker

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',

Dotless Vector Marker

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',

Vector Flag

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.
查看更多
登录 后发表回答