谷歌地圖 API 添加形狀

最近加班真是累成狗啊,每天10點之後下班。還有其餘的事情,總之都是要死要死的感受,苦逼的程序員。
谷歌地圖形狀官網:https://developers.google.com...javascript

簡介

您能夠向地圖添加各類形狀。形狀是地圖上與某個緯度/經度座標綁定的對象。可用的形狀以下:多邊形矩形。您還能夠將形狀配置爲可供用戶進行編輯或拖動。java

多段線

如需在地圖上繪製線,請使用多段線。 Polyline 類在地圖上定義線性相連線段疊層。Polyline 對象包含一個 LatLng 位置數組,它建立的一系列線段以有序方式將這些位置鏈接起來。程序員

1. 添加多段線數組

Polyline 構造函數帶有一組用於指定線的 LatLng 座標的 PolylineOptions,以及一組用於調整多段線視覺行爲的樣式。mvc

Polyline 對象在地圖上繪製爲一系列直線線段。您能夠在構建線時在PolylineOptions 內指定線描邊的自定義顏色、粗細和不透明度,也可在構建後更改這些屬性。多段線支持下列描邊樣式:app

  • strokeColor 指定 "#FFFFFF" 格式的十六進制 HTML 顏色。Polyline 類不支持命名顏色。ide

  • strokeOpacity 指定一個介於 0.01.0 的數值,用於肯定線顏色的不透明度。默認值爲 1.0。函數

  • strokeWeight 指定線的寬度(單位:像素)。動畫

    多段線的 editable 屬性指定用戶是否能夠編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也能夠經過設置 draggable 屬性來容許用戶拖動線。this

//此示例建立一個2-pixel-wide紅色線顯示的路徑威廉的第一次跨越太平洋的飛行,途經奧克蘭、CA、布里斯班、澳大利亞。
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {lat: 0, lng: -180},
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  var 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}
  ];
  var flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  flightPath.setMap(map);
}

2. 移除多段線

如需移除地圖中的多段線,請調用 setMap() 方法,並傳遞 null 做爲其自變量。在下例中,flightPath 是一個多段線對象:

`flightPath.setMap(null);`
        // This example adds a UI control allowing users to remove the polyline from the map.
    
    var flightPath;
    var map;
    function initMap() {
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 3,
        center: {lat: 0, lng: -180},
        mapTypeId: google.maps.MapTypeId.TERRAIN
      });
    
      var flightPathCoordinates = [
        {lat: 37.772, lng: -122.214},
        {lat: 21.291, lng: -157.821},
        {lat: -18.142, lng: 178.431},
        {lat: -27.467, lng: 153.027}
      ];
    
      flightPath = new google.maps.Polyline({
        path: flightPathCoordinates,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
      });
    
      addLine();
    }
    
    function addLine() {
      flightPath.setMap(map);
    }
    
    function removeLine() {
      flightPath.setMap(null);
    }

3. 檢查多段線

多段線以 LatLng 對象數組形式指定一系列座標。這些座標決定線的路徑。如需檢索這些座標,請調用 getPath(),後者將返回 MVCArray 類型的數組。您能夠利用下列操做操縱和檢查該數組:

  • getAt() 返回給定以零爲起點索引值處的 LatLng

  • insertAt() 在給定以零爲起點索引值處插入傳遞的 LatLng。請注意,該索引值處的任何現有座標都將前移

  • removeAt() 移除給定以零爲起點索引值處的 LatLng

注:不能直接利用 mvcArray[i] 語法檢索數組的第 i 個元素。您必須使用 mvcArray.getAt(i)

// This example creates an interactive map which constructs a polyline based on
// user clicks. Note that the polyline only appears once its path property
// contains two LatLng coordinates.

var poly;
var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {lat: 41.879, lng: -87.624}  // Center the map on Chicago, USA.
  });

  poly = new google.maps.Polyline({
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3
  });
  poly.setMap(map);

  // Add a listener for the click event
  map.addListener('click', addLatLng);
}

// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
  var path = poly.getPath();

  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear.
  path.push(event.latLng);

  // Add a new marker at the new plotted point on the polyline.
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
}

4. 定製多段線

能夠向多段線添加符號形式的基於矢量的圖像。您能夠經過組合使用符號和 PolylineOptions 類對地圖上多段線的外觀進行充分的控制。請參閱符號,瞭解有關箭頭、虛線、自定義符號及動畫符號的信息。

多邊形

多邊形表示由閉合路徑(或環路)封閉的區域,由一系列座標定義。Polygon 對象與 Polyline 對象相似,由於它們都包含一系列有序的座標。多邊形使用描邊和填充區繪製。您能夠爲多邊形邊緣(描邊)定義自定義顏色、粗細和不透明度,以及爲封閉區域(填充區)定義自定義顏色和不透明度。顏色應以十六進制 HTML 格式表示。不支持顏色名稱。

Polygon 對象可描述複雜形狀,其中包括:

  • 由單個多邊形定義的多個不連續區域

    • 帶孔的區域

    • 一個或多個區域的交集

1. 添加多變形

因爲多邊形區域可能包括幾個不一樣路徑,所以 Polygon 對象的 paths 屬性指定的是數組的數組,每一個數組的類型均爲 MVCArray。每一個數組定義的都是不一樣的有序 LatLng 座標序列。

對於只包括一個路徑的簡單多邊形,您能夠利用單個 LatLng 座標數組構建 Polygon。構建時,Google Maps JavaScript API 將在於 paths 屬性內存儲該簡單數組時將其轉換成數組的數組。API 爲包括一個路徑的多邊形提供了一個簡單的 getPath() 方法。

注:若是您以這種方式構建一個簡單的多邊形,仍需經過以 MVCArray 形式操縱路徑來檢索多邊形的值。

多邊形的 editable 屬性指定用戶是否能夠編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也能夠經過設置 draggable 屬性來容許用戶拖動形狀。

// This example creates a simple polygon representing the Bermuda Triangle.
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 5,
        center: {
            lat: 24.886,
            lng: -70.268
        },
        mapTypeId: google.maps.MapTypeId.TERRAIN
    });

    // Define the LatLng coordinates for the polygon's path.
    var triangleCoords = [{
        lat: 25.774,
        lng: -80.190
    }, {
        lat: 18.466,
        lng: -66.118
    }, {
        lat: 32.321,
        lng: -64.757
    }, {
        lat: 25.774,
        lng: -80.190
    }];

    // Construct the polygon.
    var bermudaTriangle = new google.maps.Polygon({
        paths: triangleCoords,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });
    bermudaTriangle.setMap(map);
}

上例中的 Polygon 包含四組 LatLng 座標,但請注意第一組座標和最後一組座標定義的位置相同,該位置用於完成環路。但在實踐中,因爲多邊形定義的是封閉區域,所以您無需定指定最後一組座標。Google Maps JavaScript API 將經過繪製一筆,將任何給定路徑的最後一個位置連回第一個位置,自動完成多邊形。

2. 移除多邊形

如需移除地圖中的多邊形,請調用 setMap() 方法,並傳遞 null 做爲其自變量。在下例中,bermudaTriangle 是一個多邊形對象:

bermudaTriangle.setMap(null);

3. 檢查多邊形

多邊形以數組的數組形式指定其座標系列,其中每一個數組的類型均爲 MVCArray。每一個「葉」數組都是一個指定單個路徑的 LatLng 座標數組。如需檢索這些座標,請調用 Polygon 對象的 getPaths() 方法。因爲該數組是 MVCArray,您須要利用下列操做操縱和檢查該數組:

  • getAt() 返回給定以零爲起點索引值處的 LatLng

  • insertAt() 在給定以零爲起點索引值處插入傳遞的 LatLng。請注意,該索引值處的任何現有座標都將前移

  • removeAt() 移除給定以零爲起點索引值處的 LatLng

矩形

除了 Polygon 泛型類外,Google Maps JavaScript API 還提供了專供 Rectangle 對象簡化其結構的類。

1. 添加矩形

RectanglePolygon 相似,您也能夠爲矩形邊緣(描邊)定義自定義顏色、粗細和不透明度,以及爲矩形內區域(填充區)定義自定義顏色和不透明度。顏色應以十六進制數值 HTML 樣式表示。

Polygon 不一樣的是,您無需爲 Rectangle 定義 paths。與多邊形不一樣,矩形具備一個 bounds 屬性,經過爲矩形指定 google.maps.LatLngBounds 來定義其形狀。

矩形的 editable 屬性指定用戶是否能夠編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也能夠經過設置 draggable 屬性來容許用戶拖動矩形。

// This example adds a red rectangle to a map.
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 11,
        center: {
            lat: 33.678,
            lng: -116.243
        },
        mapTypeId: google.maps.MapTypeId.TERRAIN
    });

    var rectangle = new google.maps.Rectangle({
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        map: map,
        bounds: {
            north: 33.685,
            south: 33.671,
            east: -116.234,
            west: -116.251
        }
    });
}

2. 移除矩形

如需移除地圖中的矩形,請調用 setMap() 方法,並傳遞 null 做爲其自變量。

rectangle.setMap(null);

請注意,以上方法不會刪除矩形,而只是從地圖中移除矩形。若是您其實是想刪除矩形,則應先將其從地圖中移除,而後將矩形自己設置爲 null。

除了 Polygon 泛型類外,Google Maps JavaScript API 還提供了專供 Circle 對象簡化其結構的類。

1. 添加圓

CirclePolygon 相似,您也能夠爲圓的邊緣(描邊)定義自定義顏色、粗細和不透明度,以及爲圓內區域(填充區)定義自定義顏色和不透明度。顏色應以十六進制數值 HTML 樣式表示。

Polygon 不一樣的是,您無需爲 Circle 定義 paths。圓具備兩個額外的形狀定義屬性:

  • center 指定圓中心的 google.maps.LatLng

  • radius 指定圓的半徑(單位:米)

    圓的 editable 屬性指定用戶是否能夠編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也能夠經過設置 draggable 屬性來容許用戶拖動圓。

// This example creates circles on the map, representing populations in North
// America.

// First, create an object containing LatLng and population for each city.
var citymap = {
  chicago: {
    center: {lat: 41.878, lng: -87.629},
    population: 2714856
  },
  newyork: {
    center: {lat: 40.714, lng: -74.005},
    population: 8405837
  },
  losangeles: {
    center: {lat: 34.052, lng: -118.243},
    population: 3857799
  },
  vancouver: {
    center: {lat: 49.25, lng: -123.1},
    population: 603502
  }
};

function initMap() {
  // Create the map.
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: 37.090, lng: -95.712},
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  // Construct the circle for each value in citymap.
  // Note: We scale the area of the circle based on the population.
  for (var city in citymap) {
    // Add the circle for this city to the map.
    var cityCircle = new google.maps.Circle({
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35,
      map: map,
      center: citymap[city].center,
      radius: Math.sqrt(citymap[city].population) * 100
    });
  }
}

2. 移除園

如需移除地圖中的圓,請調用 setMap() 方法,並傳遞 null 做爲其自變量。

circle.setMap(null);

請注意,以上方法不會刪除圓,而只是從地圖中移除圓。若是您其實是想刪除圓,則應先將其從地圖中移除,而後將圓自己設置爲 null。

可由用戶編輯和拖動的形狀

將形狀設置爲可編輯會給形狀添加手柄,用戶能夠利用手柄直接在地圖上對形狀進行位置調整、從新塑形和尺寸調整。您還能夠將形狀設置爲可拖動,以便用戶將其移至地圖上的其餘地點。

用戶對對象作出的更改沒法跨會話存留。若是您想保存用戶的編輯,必須自行採集和存儲信息。

1. 將形狀設置爲可編輯

可經過在形狀的選項中將 editable 設置爲 true,將任何形狀(多段線、多邊形、圓和矩形)設置爲可由用戶編輯。

2. 將形狀設置爲可拖動

默認狀況下,在地圖上繪製的形狀位置固定。如需容許用戶將形狀拖動到地圖上的其餘位置,請在形狀的選項中將 draggable 設置爲 true

3. 偵聽編輯事件

編輯形狀時,會在編輯完成時觸發事件。下面列出了這些事件。

形狀 事件
radius_changed、center_changed
多邊形 insert_at、remove_at、set_at,必須在多邊形的路徑上設置偵聽器,若是多邊形有多個路徑,必須在每一個路徑上設置偵聽器
多段線 insert_at、remove_at、set_at,必須在多段線的路徑上設置偵聽器
矩形 bounds_changed

一些相關的代碼段:

google.maps.event.addListener(circle, 'radius_changed', function() {
  console.log(circle.getRadius());
});

google.maps.event.addListener(outerPath, 'set_at', function() {
  console.log('Vertex moved on outer path.');
});

google.maps.event.addListener(innerPath, 'insert_at', function() {
  console.log('Vertex removed from inner path.');
});

google.maps.event.addListener(rectangle, 'bounds_changed', function() {
  console.log('Bounds changed.');
});

4. 偵聽拖動事件

拖動形狀時,會在拖動操做開始和結束時以及拖動期間觸發事件。對於多段線、多邊形、圓和矩形,將會觸發下列事件。

事件 說明
dragstart 當用戶開始拖動形狀時觸發
drag 在用戶拖動形狀期間反覆觸發
dragend 當用戶中止拖動形狀時觸發
如需瞭解更多關於處理事件的內容,請參閱[有關事件的文檔][2]。


 


  [1]: https://developers.google.com/maps/documentation/javascript/symbols
相關文章
相關標籤/搜索