You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Map中通过setStyle为GeoJSON LineString设置虚线

如何为Google Maps GeoJSON LineString设置虚线样式?

你可以通过在setStyle配置中添加strokeDashArray属性来实现GeoJSON LineString的虚线效果,完全不需要用到Polyline。

具体来说,strokeDashArray接受一个数值数组,数组里的元素交替代表实线段长度和空白间隔长度。比如[10, 5]就表示绘制10像素的实线,接着留5像素的空白,重复这个模式直到线条结束。你可以根据需求调整这些数值来改变虚线的疏密和样式。

下面是修改后的完整代码:

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lng: -73.945259, lat: 41.133659},
    zoom: 15
  });
  map.data.addGeoJson({
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
        "properties": {"prop0": "value0"}
      },
      {
        "type": "Feature",
        "geometry": {
          "type": "LineString",
          "coordinates": [
            [-73.945259094199997, 41.133659362800003],
            [-73.945625305199997, 41.178726196299998],
            [-73.978820800799994, 41.2158432007],
            [-73.978256225600006, 41.249233245799999],
            [-73.954887390099998, 41.288650512700002],
            [-73.986076354999994, 41.322223663300001],
            [-73.965789794900004, 41.352313995400003],
            [-73.957283020000006, 41.382507324199999],
            [-73.968963622999993, 41.410072326700003],
            [-73.989562988299994, 41.439929962199997],
            [-74.015953064000001, 41.464096069299998],
            [-74.006843566900002, 41.499134063699998],
            [-73.999168396000002, 41.5377388],
            [-73.9613571167, 41.581764221199997],
            [-73.956344604500003, 41.627635955800002],
            [-73.948852539100002, 41.678043365500002],
            [-73.946556091299996, 41.729282379200001],
            [-73.9569854736, 41.7779464722],
            [-73.9701004028, 41.828430175800001],
            [-73.985443115199999, 41.881973266599999],
            [-74.006584167499994, 41.924633026099997],
            [-73.991699218799994, 41.975730896000002],
            [-73.982696533199999, 42.033111572300001],
            [-73.962783813499996, 42.085037231400001]
          ]
        }
      }]
  });
  map.data.setStyle({
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 10,
    // 添加这一行实现虚线效果
    strokeDashArray: [10, 5]
  });
}
google.maps.event.addDomListener(window, "load", initMap);

你只需要在setStyle的配置对象里加入strokeDashArray,并根据自己的需求调整数组中的数值即可——数值越大,虚线的线段和间隔就越长,线条看起来越稀疏;数值越小则反之。

内容的提问来源于stack exchange,提问作者DCM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:28:52