如何在Google Maps API v3中使用SVG标记

How to use SVG markers in Google Maps API v3

我可以将转换后的image.svg用作Google地图图标。 我正在将我的png图像转换为svg,我想使用可旋转的google map符号。 我已经尝试使用Google地图符号,但是我想要一个像汽车,人等的图标。这就是为什么我将一些png文件转换为svg的原因,就像这个示例网站一样,他对这些http:/ /www.goprotravelling.com/


您可以使用SVG路径符号来呈现图标。

有关更多信息,请参见Google文档。

这是一个基本示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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: event.latLng,
    map: map,
    draggable: false,
    icon: icon
});

这是有关如何显示和缩放标记SVG图标的工作示例:

JSFiddle演示

编辑:

另一个带有复杂图标的示例:

JSFiddle演示

编辑2:

这是如何将SVG文件作为图标的方法:

JSFiddle演示


如果您不仅需要完整的svg,而且希望在客户端进行修改(例如,更改文本,隐藏详细信息等),则可以使用包含svg的备用数据" URL":

1
2
var svg = '<svg width="400" height="110"><rect width="300" height="100" /></svg>';
icon.url = 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg);

JavaScript(Firefox)btoa()用于从SVG文本获取base64编码。您还可以使用http://dopiaza.org/tools/datauri/index.php生成基本数据URL。

这是一个完整的jsfiddle示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript">
    </head>
    <body>
       
        <script type="text/javascript">
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: new google.maps.LatLng(-33.92, 151.25),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var template = [
                '<?xml version="1.0"?>',
                    '<svg width="26px" height="26px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">',
                        '<circle stroke="#222" fill="{{ color }}" cx="50" cy="50" r="35"/>',
                    '</svg>'
                ].join('
');
            var svg = template.replace('{{ color }}', '#800');

            var docMarker = new google.maps.Marker({
                position: new google.maps.LatLng(-33.92, 151.25),
                map: map,
                title: 'Dynamic SVG Marker',
                icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
            });

            var docMarker = new google.maps.Marker({
                position: new google.maps.LatLng(-33.95, 151.25),
                map: map,
                title: 'Dynamic SVG Marker',
                icon: { url: 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
            });
       
    </body>
</html>

附加信息可以在这里找到。

避免使用base64编码:

为了避免base64编码,可以将'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg)替换为'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg)

这应该适用于IE9以下的现代浏览器。
优点是encodeURIComponent是默认的js函数,并且在所有现代浏览器中都可用。您可能还会获得较小的链接,但需要对此进行测试,并考虑在svg中使用'而不是"

另请参阅优化数据URI中的SVG。

IE支持:
为了在IE中支持SVG标记,需要进行两个小的改动,如下所述:IE中的SVG标记。我更新了示例代码以支持IE。


我知道这篇文章有些陈旧,但是我在SO上看到了很多糟糕的信息,以至于我大喊大叫。因此,我不得不用一种我所知道的完全不同的方法投入我的两分钱,因为我在很多地图上都可靠地使用了它。除此之外,我相信OP也希望能够围绕地图点旋转箭头标记,这与围绕其自身的x,y轴旋转图标不同,后者会更改箭头标记指向地图的位置。

首先,请记住我们正在使用Google地图和SVG,因此我们必须适应Google为其标记(或实际上是符号)部署SVG实现的方式。 Google将其SVG标记图片的锚点设置为0,0,而不是SVG viewBox的左上角。为了解决这个问题,您必须以不同的方式绘制SVG图像,以向Google提供所需的内容...是的,答案是您在SVG编辑器(Illustrator,Inkscape等)中实际创建SVG路径的方式。 )。

第一步是摆脱viewBox。这可以通过将XML中的viewBox设置为0来完成...是的,只是一个零而不是viewBox的通常四个参数。这将关闭视图框(是的,这在语义上是正确的)。执行此操作时,您可能会注意到图像的大小立即跳跃,这是因为svg不再具有缩放图像的基础(viewBox)。因此,我们通过将宽度和高度设置为希望图像在SVG编辑器的XML编辑器中的实际像素数来直接创建该引用。

通过在XML编辑器中设置svg图像的宽度和高度,您可以创建用于缩放图像的基线,并且默认情况下,此大小对于标记比例属性为1。您会看到它对于标记的动态缩放具有的优势。

现在,您已经确定了图像的大小,然后移动图像,直到图像的锚点位于svg编辑器的0,0坐标上为止。完成此操作后,复制svg路径的d属性值。您会注意到大约一半的数字是负数,这是因为将锚点对准图像的0,0而不是viewBox。

然后,使用此技术可以让您围绕地图上的经纬度点正确旋转标记。这是将svg标记上的点绑定到标记位置的纬度和经度的唯一可靠方法。

我试图为此创建一个JSFiddle,但是在那里实现存在一些错误,这是我不喜欢重新解释代码的原因之一。因此,相反,我在下面提供了一个完全独立的示例,您可以尝试,修改并用作参考。这是我在JSFiddle尝试的相同代码,但失败了,但是它在Firebug中航行时没有任何提示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport"  content="width=device-width, initial-scale=1" />
    <meta name="author"    content="Drew G. Stimson, Sr. ( Epiphany )" />
    Create Draggable and Rotatable SVG Marker
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false">
    <style type="text/css">
      #document_body {
        margin:0;
        border: 0;
        padding: 10px;
        font-family: Arial,sans-serif;
        font-size: 14px;
        font-weight: bold;
        color: #f0f9f9;
        text-align: center;
        text-shadow: 1px 1px 1px #000;
        background:#1f1f1f;
      }
      #map_canvas, #rotation_control {
        margin: 1px;
        border:1px solid #000;
        background:#444;
        -webkit-border-radius: 4px;
           -moz-border-radius: 4px;
                border-radius: 4px;
      }
      #map_canvas {
        width: 100%;
        height: 360px;
      }
      #rotation_control {
        width: auto;
        padding:5px;
      }
      #rotation_value {
        margin: 1px;
        border:1px solid #999;
        width: 60px;
        padding:2px;
        font-weight: bold;
        color: #00cc00;
        text-align: center;
        background:#111;
        border-radius: 4px;
      }
</style>

<script type="text/javascript">
  var map, arrow_marker, arrow_options;
  var map_center = {lat:41.0, lng:-103.0};
  var arrow_icon = {
    path: 'M -1.1500216e-4,0 C 0.281648,0 0.547084,-0.13447 0.718801,-0.36481 l 17.093151,-22.89064 c 0.125766,-0.16746 0.188044,-0.36854 0.188044,-0.56899 0,-0.19797 -0.06107,-0.39532 -0.182601,-0.56215 -0.245484,-0.33555 -0.678404,-0.46068 -1.057513,-0.30629 l -11.318243,4.60303 0,-26.97635 C 5.441639,-47.58228 5.035926,-48 4.534681,-48 l -9.06959,0 c -0.501246,0 -0.906959,0.41772 -0.906959,0.9338 l 0,26.97635 -11.317637,-4.60303 c -0.379109,-0.15439 -0.812031,-0.0286 -1.057515,0.30629 -0.245483,0.33492 -0.244275,0.79809 0.0055,1.13114 L -0.718973,-0.36481 C -0.547255,-0.13509 -0.281818,0 -5.7002158e-5,0 Z',
    strokeColor: 'black',
    strokeOpacity: 1,
    strokeWeight: 1,
    fillColor: '#fefe99',
    fillOpacity: 1,
    rotation: 0,
    scale: 1.0
  };

function init(){
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: map_center,
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.HYBRID
  });
  arrow_options = {
    position: map_center,
    icon: arrow_icon,
    clickable: false,
    draggable: true,
    crossOnDrag: true,
    visible: true,
    animation: 0,
    title: 'I am a Draggable-Rotatable Marker!'
  };
  arrow_marker = new google.maps.Marker(arrow_options);
  arrow_marker.setMap(map);
}
function setRotation(){
  var heading = parseInt(document.getElementById('rotation_value').value);
  if (isNaN(heading)) heading = 0;
  if (heading < 0) heading = 359;
  if (heading > 359) heading = 0;
  arrow_icon.rotation = heading;
  arrow_marker.setOptions({icon:arrow_icon});
  document.getElementById('rotation_value').value = heading;
}

</head>
<body id="document_body" onload="init();">
 
    <small>Enter heading to rotate marker</small>
    Heading&deg;<input id="rotation_value" type="number" size="3" value="0" onchange="setRotation();" />
    <small>Drag marker to place marker</small>
   
   
</body>
</html>

这正是Google所做的,因为Google Maps API的SYMBOL类中只有很少的符号可用,因此如果这不能说服您...
无论如何,我希望这能帮助您正确地为Google地图制作和设置SVG标记。


是的,您可以将.svg文件用作图标,就像可以使用.png或其他图像文件格式一样。只需将图标的url设置为.svg文件所在的目录即可。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
var icon = {
        url: 'path/to/images/car.svg',
        size: new google.maps.Size(sizeX, sizeY),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(sizeX/2, sizeY/2)
};

var marker = new google.maps.Marker({
        position: event.latLng,
        map: map,
        draggable: false,
        icon: icon
});


情况越来越好,现在您可以使用SVG文件。

1
2
3
4
5
6
        marker = new google.maps.Marker({
            position: {lat: 36.720426, lng: -4.412573},
            map: map,
            draggable: true,
            icon:"img/tree.svg"
        });


正如该线程中的其他人所提到的,不要忘记在svg中显式设置width和height属性,如下所示:

1
2
3
<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 26 42"
     width="26px" height="42px">

如果您不这样做,那么任何js操作都无法帮助您,因为gmaps将没有参考框架,并且始终使用标准尺寸。

(我知道它在某些评论中已经提到,但是很容易被忽略。此信息在各种情况下对我都有帮助)


好!我很快在网络上做到了这一点,我尝试了两种方法来创建自定义的Google Map标记,此运行代码使用canvg.js是与浏览器的最佳兼容性。Commented-Out代码目前不支持IE11。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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 = $("");

  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;

  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;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  Your Custom Marker
  <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>
 
    <script src="https://canvg.github.io/canvg/canvg.js">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</body>

</html>


您需要传递optimized: false

例如。

1
2
var img = { url: 'img/puff.svg', scaledSide: new google.maps.Size(5, 5) };
new google.maps.Marker({position: this.mapOptions.center, map: this.map, icon: img, optimized: false,});

没有通过optimized: false,我的svg显示为静态图像。