简体   繁体   中英

Javascript, Change google map marker color

May I know a way to change the Google Map marker color via Javascript.. I am new at this and any help would be much appreciated, Thank you.

I used the following code to create a marker

 marker = new google.maps.Marker({
     position: new google.maps.LatLng(locations[i][1], 
     locations[i][2]),
     animation: google.maps.Animation.DROP,
     map: map
 });

In Google Maps API v3 you can try changing marker icon. For example for green icon use:

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 colors:

Etc.

You can use the strokeColor property:

var marker = new google.maps.Marker({
    id: "some-id",
    icon: {
        path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
        strokeColor: "red",
        scale: 3
    },
    map: map,
    title: "some-title",
    position: myLatlng
});

See this page for other possibilities.

You can use this code it works fine.

 var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");

 var marker = new google.maps.Marker({
            position: yourlatlong,
            icon: pinImage,
            map: map
        });

see Example here

you can use the google chart api and generate any color with rgb code on the fly:

example: marker with #ddd color:

http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ddd

include as stated above with

 var marker = new google.maps.Marker({
    position: marker,
    title: 'Hello World',
    icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ddd'
});

I have 4 ships to set on one single map, so I use the Google Developers example and then twisted it

https://developers.google.com/maps/documentation/javascript/examples/icon-complex

In the function bellow I set 3 more color options:

function setMarkers(map, locations) {
...
var image = {
    url: 'img/bullet_amarelo.png',
    // This marker is 20 pixels wide by 32 pixels tall.
    size: new google.maps.Size(40, 40),
    // The origin for this image is 0,0.
    origin: new google.maps.Point(0,0),
    // The anchor for this image is the base of the flagpole at 0,32.
    anchor: new google.maps.Point(0, 40)
  };
  var image1 = {
            url: 'img/bullet_azul.png',
            // This marker is 20 pixels wide by 32 pixels tall.
            size: new google.maps.Size(40, 40),
            // The origin for this image is 0,0.
            origin: new google.maps.Point(0,0),
            // The anchor for this image is the base of the flagpole at 0,32.
            anchor: new google.maps.Point(0, 40)
          };
  var image2 = {
          url: 'img/bullet_vermelho.png',
          // This marker is 20 pixels wide by 32 pixels tall.
          size: new google.maps.Size(40, 40),
          // The origin for this image is 0,0.
          origin: new google.maps.Point(0,0),
          // The anchor for this image is the base of the flagpole at 0,32.
          anchor: new google.maps.Point(0, 40)
        };
  var image3 = {
          url: 'img/bullet_verde.png',
          // This marker is 20 pixels wide by 32 pixels tall.
          size: new google.maps.Size(40, 40),
          // The origin for this image is 0,0.
          origin: new google.maps.Point(0,0),
          // The anchor for this image is the base of the flagpole at 0,32.
          anchor: new google.maps.Point(0, 40)
        };
...
}

And in the FOR bellow I set one color for each ship:

for (var i = 0; i < locations.length; i++) {
...
    if (i==0) var imageV=image;
    if (i==1) var imageV=image1;
    if (i==2) var imageV=image2;
    if (i==3) var imageV=image3;
...
# remember to change icon: image to icon: imageV
}

The final result:

http://www.mercosul-line.com.br/site/teste.html

I suggest using the Google Charts API because you can specify the text, text color, fill color and outline color, all using hex color codes, eg #FF0000 for red. You can call it as follows:

function getIcon(text, fillColor, textColor, outlineColor) {
  if (!text) text = '•'; //generic map dot
  var iconUrl = "http://chart.googleapis.com/chart?cht=d&chdp=mapsapi&chl=pin%27i\\%27[" + text + "%27-2%27f\\hv%27a\\]h\\]o\\" + fillColor + "%27fC\\" + textColor + "%27tC\\" + outlineColor + "%27eC\\Lauto%27f\\&ext=.png";
  return iconUrl;
}

Then, when you create your marker you just set the icon property as such, where the myColor variables are hex values (minus the hash sign):

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(locations[i][1], locations[i][2]),
  animation: google.maps.Animation.DROP,
  map: map,
  icon: getIcon(null, myColor, myColor2, myColor3)
});

You can use http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=•|FF0000 , which is a bit easier to decipher, as an alternate URL if you only need to set text and fill color.

khurram's answer refers to a 3rd party site that redirects to the Google Charts API. This means if that person takes down their server you're hosed. I prefer having the flexibility the Google API offers as well as the reliability of going directly to Google. Just make sure you specify a value for each of the colors or it won't work.

I really liked the answer given by Bahadır Yağan except I didn't like depending on a limited set of icons given by Google or an external API to generate my marker icons. Here is the initial solution:

 var marker = new google.maps.Marker({ id: "some-id", icon: { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, strokeColor: "red", scale: 3 }, map: map, title: "some-title", position: myLatlng }); 

And here is my improved solution:

var marker = new google.maps.Marker({
            position: myLatlng,
            icon:{
                path: 'm 12,2.4000002 c -2.7802903,0 -5.9650002,1.5099999 -5.9650002,5.8299998 0,1.74375 1.1549213,3.264465 2.3551945,4.025812 1.2002732,0.761348 2.4458987,0.763328 2.6273057,2.474813 L 12,24 12.9825,14.68 c 0.179732,-1.704939 1.425357,-1.665423 2.626049,-2.424188 C 16.809241,11.497047 17.965,9.94 17.965,8.23 17.965,3.9100001 14.78029,2.4000002 12,2.4000002 Z',
                fillColor: '#00FF00',
                fillOpacity: 1.0,
                strokeColor: '#000000',
                strokeWeight: 1,
                scale: 2,
                anchor: new google.maps.Point(12, 24),
            },
        });

I wanted a specific pin icon so I went and made one with inkscape, then opened the SVG file and copied the svg path into the path into the code, but this works with any SVG path that you put in the "path" attribute of the icon object.

Here is the result:

在此输入图像描述

To expand upon the accepted answer, you can create custom MarkerImages of any color using the API at http://chart.googleapis.com

In addition to changing color, this also changes marker shape, which may be unwanted.

const marker = new window.google.maps.Marker(
        position: markerPosition,
        title: markerTitle,
        map: map)
marker.addListener('click', () => marker.setIcon(changeIcon('00ff00'));)

const changeIcon = (newIconColor) => {
    const newIcon = new window.google.maps.MarkerImage(
        `http://chart.googleapis.com/chart?                                      
        chst=d_map_spin&chld=1.0|0|${newIconColor}|60|_|%E2%80%A2`,
        new window.google.maps.Size(21, 34),
        new window.google.maps.Point(0, 0),
        new window.google.maps.Point(10, 34),
        new window.google.maps.Size(21,34)
    );
    return newIcon
}

Source: free udacity course on google maps apis

2022 Solution: Advanced Markers

Hi Google Maps JavaScript API developer here.

Google recently announced the new Advanced Markers , it has some really cool features including customizing the default marker's color, glyph, glyph color and scale etc. And we've been trying to improve the performance.

The new APIs are still in beta, we would love your feedback!

在此处输入图像描述

we can do this by adding an icon property and specifying a URL like mention below:

icon: {
url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" }

let map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 8
  });

  let marker = new google.maps.Marker({
    map: map,
    position: {lat: -34.397, lng: 150.644},
    icon: {
      url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
    }
  });
}

var map_marker = $(".map-marker").children("img").attr("src") var pinImage = new google.maps.MarkerImage(map_marker);

     var marker = new google.maps.Marker({
      position: uluru,
      map: map,
      icon: pinImage
    });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM