形状和线条

请选择平台: Android iOS JavaScript

您可以向地图添加各种形状。形状是地图上的一种对象,与某个纬度/经度坐标相关联。可用的形状包括以下几种:线条多边形圆形矩形。您还可以配置形状,让用户可以修改或拖动形状

多段线

要在地图上绘制线条,可以使用多段线。Polyline 类可定义地图上的线性相连线段叠加层。Polyline 对象包含一组 LatLng 位置,并可创建一系列线段,依照先后次序将这些位置连接起来。

添加多段线

Polyline 构造函数可接受一组 PolylineOptions(用于指定线条的 LatLng 坐标)和一组样式(用于调整多段线的视觉行为)。

Polyline 对象在地图上绘制为一系列直线段。您可以在构建线条时通过 PolylineOptions 指定线条描边的自定义颜色、粗细和不透明度,也可以在构建后更改这些属性。多段线支持下列描边样式:

  • strokeColor,用于指定 "#FFFFFF" 格式的十六进制 HTML 颜色。Polyline 类不支持使用颜色名称来指定颜色。
  • strokeOpacity,用于指定介于 0.01.0 之间的一个数值,以确定线条颜色的不透明度。默认值为 1.0
  • strokeWeight,用于指定线条的宽度(以像素为单位)。

多段线的 editable 属性用于指定用户是否可以修改相应形状。请参阅下面的用户可修改的形状。同样,您可以设置 draggable 属性,允许用户拖动相应线条

TypeScript

// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 3,
      center: { lat: 0, lng: -180 },
      mapTypeId: "terrain",
    }
  );

  const flightPlanCoordinates = [
    { lat: 37.772, lng: -122.214 },
    { lat: 21.291, lng: -157.821 },
    { lat: -18.142, lng: 178.431 },
    { lat: -27.467, lng: 153.027 },
  ];
  const flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    geodesic: true,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2,
  });

  flightPath.setMap(map);
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 3,
    center: { lat: 0, lng: -180 },
    mapTypeId: "terrain",
  });
  const flightPlanCoordinates = [
    { lat: 37.772, lng: -122.214 },
    { lat: 21.291, lng: -157.821 },
    { lat: -18.142, lng: 178.431 },
    { lat: -27.467, lng: 153.027 },
  ];
  const flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    geodesic: true,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2,
  });

  flightPath.setMap(map);
}

window.initMap = initMap;
查看示例

试用示例