谷歌地圖API添加形狀
簡介
您可以向地圖添加各種形狀。形狀是地圖上與某個緯度/經(jīng)度坐標(biāo)綁定的對象??捎玫男螤钊缦拢壕€、多邊形、圓和矩形。您還可以將形狀配置為可供用戶進(jìn)行編輯或拖動。
多段線
如需在地圖上繪制線,請使用多段線。 Polyline 類在地圖上定義線性相連線段疊層。Polyline 對象包含一個 LatLng 位置數(shù)組,它創(chuàng)建的一系列線段以有序方式將這些位置連接起來。
1. 添加多段線
Polyline 構(gòu)造函數(shù)帶有一組用于指定線的 LatLng 坐標(biāo)的 PolylineOptions,以及一組用于調(diào)整多段線視覺行為的樣式。
Polyline 對象在地圖上繪制為一系列直線線段。您可以在構(gòu)建線時在PolylineOptions 內(nèi)指定線描邊的自定義顏色、粗細(xì)和不透明度,也可在構(gòu)建后更改這些屬性。多段線支持下列描邊樣式:
- strokeColor 指定 "#FFFFFF" 格式的十六進(jìn)制 HTML 顏色。Polyline 類不支持命名顏色。
- strokeOpacity 指定一個介于 0.0 和 1.0 的數(shù)值,用于確定線顏色的不透明度。默認(rèn)值為 1.0。
- strokeWeight 指定線的寬度(單位:像素)。
多段線的 editable 屬性指定用戶是否可以編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也可以通過設(shè)置 draggable 屬性來允許用戶拖動線。
- //此示例創(chuàng)建一個2-pixel-wide紅色線顯示的路徑威廉的***次跨越太平洋的飛行,途經(jīng)奧克蘭、CA、布里斯班、澳大利亞。
- unction 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. 移除多段線
如需移除地圖中的多段線,請調(diào)用 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 對象數(shù)組形式指定一系列坐標(biāo)。這些坐標(biāo)決定線的路徑。如需檢索這些坐標(biāo),請調(diào)用 getPath(),后者將返回MVCArray 類型的數(shù)組。您可以利用下列操作操縱和檢查該數(shù)組:
- getAt() 返回給定以零為起點(diǎn)索引值處的 LatLng
- insertAt() 在給定以零為起點(diǎn)索引值處插入傳遞的 LatLng。請注意,該索引值處的任何現(xiàn)有坐標(biāo)都將前移
- removeAt() 移除給定以零為起點(diǎn)索引值處的 LatLng
注:不能直接利用 mvcArray[i] 語法檢索數(shù)組的第 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 類對地圖上多段線的外觀進(jìn)行充分的控制。請參閱符號,了解有關(guān)箭頭、虛線、自定義符號及動畫符號的信息。
多邊形
多邊形表示由閉合路徑(或環(huán)路)封閉的區(qū)域,由一系列坐標(biāo)定義。Polygon 對象與 Polyline 對象類似,因為它們都包含一系列有序的坐標(biāo)。多邊形使用描邊和填充區(qū)繪制。您可以為多邊形邊緣(描邊)定義自定義顏色、粗細(xì)和不透明度,以及為封閉區(qū)域(填充區(qū))定義自定義顏色和不透明度。顏色應(yīng)以十六進(jìn)制 HTML 格式表示。不支持顏色名稱。
Polygon 對象可描述復(fù)雜形狀,其中包括:
- 由單個多邊形定義的多個不連續(xù)區(qū)域
帶孔的區(qū)域
一個或多個區(qū)域的交集
1. 添加多變形
由于多邊形區(qū)域可能包括幾個不同路徑,因此 Polygon 對象的 paths 屬性指定的是數(shù)組的數(shù)組,每個數(shù)組的類型均為 MVCArray。每個數(shù)組定義的都是不同的有序 LatLng 坐標(biāo)序列。
對于只包括一個路徑的簡單多邊形,您可以利用單個 LatLng 坐標(biāo)數(shù)組構(gòu)建 Polygon。構(gòu)建時,Google Maps JavaScript API 將在于 paths 屬性內(nèi)存儲該簡單數(shù)組時將其轉(zhuǎn)換成數(shù)組的數(shù)組。API 為包括一個路徑的多邊形提供了一個簡單的 getPath() 方法。
注:如果您以這種方式構(gòu)建一個簡單的多邊形,仍需通過以 MVCArray 形式操縱路徑來檢索多邊形的值。
多邊形的 editable 屬性指定用戶是否可以編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也可以通過設(shè)置 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 坐標(biāo),但請注意***組坐標(biāo)和***一組坐標(biāo)定義的位置相同,該位置用于完成環(huán)路。但在實(shí)踐中,由于多邊形定義的是封閉區(qū)域,因此您無需定指定***一組坐標(biāo)。Google Maps JavaScript API 將通過繪制一筆,將任何給定路徑的***一個位置連回***個位置,自動完成多邊形。
2. 移除多邊形
如需移除地圖中的多邊形,請調(diào)用 setMap() 方法,并傳遞 null 作為其自變量。在下例中,bermudaTriangle 是一個多邊形對象:
- bermudaTriangle.setMap(null);
3. 檢查多邊形
多邊形以數(shù)組的數(shù)組形式指定其坐標(biāo)系列,其中每個數(shù)組的類型均為 MVCArray。每個“葉”數(shù)組都是一個指定單個路徑的 LatLng 坐標(biāo)數(shù)組。如需檢索這些坐標(biāo),請調(diào)用 Polygon 對象的 getPaths() 方法。由于該數(shù)組是 MVCArray,您需要利用下列操作操縱和檢查該數(shù)組:
- getAt() 返回給定以零為起點(diǎn)索引值處的 LatLng
- insertAt() 在給定以零為起點(diǎn)索引值處插入傳遞的 LatLng。請注意,該索引值處的任何現(xiàn)有坐標(biāo)都將前移
- removeAt() 移除給定以零為起點(diǎn)索引值處的 LatLng
矩形
除了 Polygon 泛型類外,Google Maps JavaScript API 還提供了*** Rectangle 對象簡化其結(jié)構(gòu)的類。
1. 添加矩形
Rectangle 與 Polygon 類似,您也可以為矩形邊緣(描邊)定義自定義顏色、粗細(xì)和不透明度,以及為矩形內(nèi)區(qū)域(填充區(qū))定義自定義顏色和不透明度。顏色應(yīng)以十六進(jìn)制數(shù)值 HTML 樣式表示。
與 Polygon 不同的是,您無需為 Rectangle 定義 paths。與多邊形不同,矩形具有一個 bounds 屬性,通過為矩形指定 google.maps.LatLngBounds 來定義其形狀。
矩形的 editable 屬性指定用戶是否可以編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也可以通過設(shè)置 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. 移除矩形
如需移除地圖中的矩形,請調(diào)用 setMap() 方法,并傳遞 null 作為其自變量。
- rectangle.setMap(null);
請注意,以上方法不會刪除矩形,而只是從地圖中移除矩形。如果您實(shí)際上是想刪除矩形,則應(yīng)先將其從地圖中移除,然后將矩形本身設(shè)置為 null。
圓
除了 Polygon 泛型類外,Google Maps JavaScript API 還提供了*** Circle 對象簡化其結(jié)構(gòu)的類。
1. 添加圓
Circle 與 Polygon 類似,您也可以為圓的邊緣(描邊)定義自定義顏色、粗細(xì)和不透明度,以及為圓內(nèi)區(qū)域(填充區(qū))定義自定義顏色和不透明度。顏色應(yīng)以十六進(jìn)制數(shù)值 HTML 樣式表示。
與 Polygon 不同的是,您無需為 Circle 定義 paths。圓具有兩個額外的形狀定義屬性:
- center 指定圓中心的 google.maps.LatLng
- radius 指定圓的半徑(單位:米)
圓的 editable 屬性指定用戶是否可以編輯形狀。請參閱下文的用戶可編輯形狀。同理,您也可以通過設(shè)置 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. 移除園
如需移除地圖中的圓,請調(diào)用 setMap() 方法,并傳遞 null 作為其自變量。
- circle.setMap(null);
請注意,以上方法不會刪除圓,而只是從地圖中移除圓。如果您實(shí)際上是想刪除圓,則應(yīng)先將其從地圖中移除,然后將圓本身設(shè)置為 null。
可由用戶編輯和拖動的形狀
將形狀設(shè)置為可編輯會給形狀添加手柄,用戶可以利用手柄直接在地圖上對形狀進(jìn)行位置調(diào)整、重新塑形和尺寸調(diào)整。您還可以將形狀設(shè)置為可拖動,以便用戶將其移至地圖上的其他地點(diǎn)。
用戶對對象做出的更改無法跨會話存留。如果您想保存用戶的編輯,必須自行采集和存儲信息。
1. 將形狀設(shè)置為可編輯
可通過在形狀的選項中將 editable 設(shè)置為 true,將任何形狀(多段線、多邊形、圓和矩形)設(shè)置為可由用戶編輯。
2. 將形狀設(shè)置為可拖動
默認(rèn)情況下,在地圖上繪制的形狀位置固定。如需允許用戶將形狀拖動到地圖上的其他位置,請在形狀的選項中將 draggable 設(shè)置為true。
3. 偵聽編輯事件
編輯形狀時,會在編輯完成時觸發(fā)事件。下面列出了這些事件。
形狀 | 事件 |
圓 | radius_changed、center_changed |
多邊形 | insert_at、remove_at、set_at,必須在多邊形的路徑上設(shè)置偵聽器,如果多邊形有多個路徑,必須在每個路徑上設(shè)置偵聽器 |
多段線 | insert_at、remove_at、set_at,必須在多段線的路徑上設(shè)置偵聽器 |
矩形 | bounds_changed |
一些相關(guān)的代碼段:
- 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. 偵聽拖動事件
拖動形狀時,會在拖動操作開始和結(jié)束時以及拖動期間觸發(fā)事件。對于多段線、多邊形、圓和矩形,將會觸發(fā)下列事件。
事件 | 說明 |
dragstart | 當(dāng)用戶開始拖動形狀時觸發(fā) |
drag | 在用戶拖動形狀期間反復(fù)觸發(fā) |
dragend | 當(dāng)用戶停止拖動形狀時觸發(fā) |