1. 程式人生 > >關於Google Map 疊加層之Polyline(折線)、Polygon(多邊形)、InfoWindow(資訊視窗)

關於Google Map 疊加層之Polyline(折線)、Polygon(多邊形)、InfoWindow(資訊視窗)

示例

—————— Polyline 折線

// 1. 從雍和宮–東直門畫一條折線
// 路徑
var path = [
new google.maps.LatLng(39.949227017559615,116.41707632263186),
new google.maps.LatLng(39.94942441423325,116.42548773010256),
new google.maps.LatLng(39.9408700359111,116.42583105285647),
new google.maps.LatLng(39.94080422885547,116.43364164550783)
];
// 折線引數
var polylineOptions = {
path: path,
geodesic: true, // 可測量的
strokeColor: “#000”, // 線條顏色 黑色
strokeOpacity: 0.5, // 透明度 50%
strokeWeight: 5 // 寬度 5畫素
};
// 建立一個Polyline的例項
var polyline1 = new google.maps.Polyline(polylineOptions);
polyline1.setMap(map); // 設定顯示到map上

效果:

這裡寫圖片描述

// 2. 再建立一個Polyline,雙擊地圖時,繪製折線
var polyline2 = new google.maps.Polyline({
strokeColor: “#f30”, // 線條顏色 紅色
strokeOpacity: 0.7, // 透明度 70%
strokeWeight: 5 // 寬度 5畫素
});
// 將折線放置在map上
polyline2.setMap(map);
// 給map新增雙擊事件
google.maps.event.addListener(map, “dblclick”, function(event){
// 獲得折線路徑
var path = polyline2.getPath();
// 在路徑的原點打一個標記
if( path.length == 0 ) {
var marker = new google.maps.Marker();
marker.setMap(map);
marker.setPosition(event.latLng);
marker.setTitle(event.latLng.toUrlValue());
}
// 在路徑上追加座標位置
// 因為路徑時一個MVCArray,我們可以簡單的追加一個新的座標位置,它將會自動出現
path.push(event.latLng);
});
}

這裡寫圖片描述

——-polygon多邊形

使用方法和Polyline類似,比較簡單

// 將故宮的範圍用多邊形Polygon勾畫出來
// 路徑
var path = [
new google.maps.LatLng(39.921421297246326,116.38527605255129),
new google.maps.LatLng(39.92175042507842,116.39566156585695),
new google.maps.LatLng(39.91200757162273,116.39613363464358),
new google.maps.LatLng(39.911810067017406,116.39184210021975),
new google.maps.LatLng(39.90720146455565,116.39197084625246),
new google.maps.LatLng(39.907036865876215,116.39068338592531),
new google.maps.LatLng(39.911810067017406,116.39008257110598),
new google.maps.LatLng(39.91171131450119,116.38583395202639)
];
// 多邊形引數
var polygonOptions = {
paths: path,
fillColor: “#f60”, // 填充色
fillOpacity: 0.3, // 填充色透明度
strokeColor: “#f00”, // 線條顏色 黑色
strokeOpacity: 0.7, // 透明度 70%
strokeWeight: 5 // 寬度 5畫素
};
var polygon1 = new google.maps.Polygon(polygonOptions);
polygon1.setMap(map); // 設定顯示到map上

效果:
這裡寫圖片描述

—————————– InfoWindow 資訊視窗

示例

// 建立一個資訊視窗,設定最大寬度為50
var infoWindow = new google.maps.InfoWindow({maxWidth:300});

// 在地圖上雙擊時,打一個標記
google.maps.event.addListener(map, "dblclick", function(event){

var marker = new google.maps.Marker();
marker.setMap(map);
marker.setPosition(event.latLng);

// 點選標記時,開啟資訊視窗
google.maps.event.addListener(marker, "click", function(){
    var content = "<b>" + marker.getPosition().toUrlValue() + "</b><br/>";
    content += "<p>" + $("#textDiv").html() + "</p>";
   infoWindow.setContent(content);  // 設定資訊視窗中的內容

   // 在map上的marker位置開啟資訊視窗
   infoWindow.open(map, marker);
 });
});

效果:

這裡寫圖片描述