首页 文章

Google Maps API 3 - 默认(点)标记的自定义标记颜色

提问于
浏览
261

我已经看到很多类似的问题(hereherehere),但他们都接受了无法解决问题的答案 . 我发现问题的最佳解决方案是StyledMarker库,它允许您为标记定义自定义颜色,但我无法使用默认标记(您在进行谷歌 Map 搜索时获得的标记) - 它只是提供带有字母的标记或带有特殊图标的标记 .

15 回答

  • 14

    在Internet Explorer中,此解决方案在ssl中不起作用 . 可以在控制台中看到错误:SEC7111:HTTPS安全性受此影响,解决方法:正如此处的用户之一建议将chart.apis.google.com替换为chart.googleapis.com以获取URL路径,以避免SSL错误 .

  • 0

    您可以使用此代码,它工作正常 .

    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
            });
    
  • 106

    我尝试了两种方法来创建自定义谷歌 Map 标记,这个运行代码使用canvg.js是浏览器的最佳兼容性 . 注释掉的代码不支持IE11 .

    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>
    
  • 1

    从谷歌 Map API 3.11版开始, Icon 对象取代了 MarkerImage . Icon支持与MarkerImage相同的参数 . 我甚至发现它更直接 .

    示例可能如下所示:

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

    了解更多信息check this site

  • 509

    您可以使用网址动态请求Google charts api中的图标图像:

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

    看起来像这样:
    default color
    图像是 21x34 像素,针尖位于 (10, 34)

    而且你还需要一个单独的阴影图像(这样它就不会与附近的图标重叠):

    http://chart.apis.google.com/chart?chst=d_map_pin_shadow
    

    看起来像这样:
    enter image description here
    图像是 40x37 像素,针尖位于 (12, 35)

    构造MarkerImage时,需要相应地设置大小和锚点:

    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));
    

    然后,您可以使用以下标记将标记添加到 Map 中:

    var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(0,0), 
                    map: map,
                    icon: pinImage,
                    shadow: pinShadow
                });
    

    只需将"FE7569"替换为您所使用的颜色代码即可 . 例如:
    default color

    green

    yellow

    归功于Jack B Nimble的灵感;)

  • 10

    如果您使用Google Maps API v3,则可以使用 setIcon ,例如

    marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
    

    或者作为标记初始化的一部分:

    marker = new google.maps.Marker({
        icon: 'http://...'
    });
    

    其他颜色:


    Blue marker

    enter image description here
    Red marker

    enter image description here
    Purple marker

    enter image description here
    Yellow marker

    enter image description here
    Green marker

    使用以下代码更新具有不同颜色的默认标记 .

    (BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)
    
  • 0

    这是使用Gooogle Maps API本身的一个很好的解决方案 . 没有外部服务,没有额外的库 . 它可以实现自定义形状和多种颜色和样式 . 该解决方案使用矢量标记,googlemaps api称之为Symbols .

    除了少数和有限的预定义符号,您可以通过指定SVG路径字符串(Spec)来制作任何颜色的任何形状 .

    要使用它,不要将“icon”标记选项设置为图像URL,而是将其设置为包含符号选项的字典 . 例如,我设法制作了一个与标准标记非常相似的符号:

    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

    我要小心将形状关键点保持在0,0,以避免必须定义标记图标居中参数 . 另一个路径示例,没有点的相同标记:

    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

    在这里你有一个非常简单和丑陋的彩旗:

    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

    您还可以使用Inkscape(GNU-GPL,multiplatform)等可视化工具创建路径 . 一些有用的提示:

    • Google API只接受单个路径,因此您必须将任何其他对象(square,cercle ...)转换为路径并将它们作为单个路径连接起来 . 路径菜单中的两个命令 .

    • 要将路径移动到(0,0),请转到路径编辑模式(F2),选择所有控制节点并拖动它们 . 使用F1移动对象不会更改路径节点坐标 .

    • 要确保参考点位于(0,0),您可以单独选择它并在顶部工具栏上手动编辑坐标 .

    • 保存SVG文件(XML)后,使用编辑器打开它,查找svg:path元素并复制'd'属性的内容 .

  • 0

    那么我用StyledMarker得到的最接近的是this .

    中间的子弹不是默认的子弹 . StyledMarker类只是构建此url并要求google api创建标记 .

    class use example使用 "%E2%80%A2" 作为您的文本,如:

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

    您需要修改StyledMarker.js以注释掉这些行:

    if (text_) {
        text_ = text_.substr(0,2);
      }
    

    因为这会将文本字符串修剪为2个字符 .

    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)
      )
    });
    
  • 2

    您好,您可以使用图标作为SVG并设置颜色 . 看到这段代码

    /*
     * 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>
    
  • 11

    我已经扩展了vokimon's answer,使得更改其他属性也更方便 .

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

    用法:

    marker.setIcon(customIcon({
      fillColor: '#fff',
      strokeColor: '#000'
    }));
    

    或者在定义新标记时:

    const marker = new google.maps.Marker({
      position: {
        lat: ...,
        lng: ...
      },
      icon: customIcon({
        fillColor: '#2ecc71'
      }),
      map: map
    });
    
  • 1

    组合一个symbol-based标记,其路径绘制轮廓,中心为'●'字符 . 您可以根据需要将点替换为其他文本('A','B'等) .

    此函数返回具有给定文本(如果有),文本颜色和填充颜色的标记的选项 . 它使用轮廓的文本颜色 .

    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
            }
        };
    }
    
  • 356

    将其更改为chart.googleapis.com以获取路径,否则SSL将无法使用

  • 6

    使用swift和谷歌 Map Api v3,这是我能够做到的最简单的方法:

    icon = GMSMarker.markerImageWithColor(UIColor.blackColor())
    

    希望它可以帮到某人 .

  • 4

    这些是服装圆形标记

    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==
    

    它们是9x9 png图像 .

    一旦他们在你的页面上,你可以将它们拖出来,你将拥有实际的png文件 .

  • 0

    我试了很长时间来改进vokimon的绘制标记,并使其更像Google Maps(并且非常成功) . 这是我得到的代码:

    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)];
    

    我也把它缩小了0.8 .

相关问题