Google Map - Static Map & API

目的

  1. 使用Google Map URL傳入參數就可以實現路線規劃功能,也可抓取目前位置進行規劃
  2. Google Static Map可以取得地圖影像

路徑規劃

  • 參數
    • saddr: 起點位置
    • daddr: 終點位置
  • 位置皆可使用 [地址] 或 [經緯度]
  • [Current+Location]可抓取目前位置
1
2
3
http://maps.google.com/maps?saddr=Current+Location&daddr=高雄夢時代
or
http://maps.google.com/maps?saddr=Current+Location&daddr=22.5961822,120.3062948

Google Static Map

  • 參數
    • center: 定義地圖中心
    • markers: 地圖標記
        1. 自訂marker樣式:color:red|label:D|22.5961822,120.3062948
        1. 地址間使用 | 分隔,如:高雄夢時代|高雄火車站
    • path: 路徑
      • 地址間使用 | 分隔,如:高雄夢時代|高雄火車站
1
2
3
https://maps.googleapis.com/maps/api/staticmap?center=22.5961822,120.3062948&markers=color:red|label:D|22.5961822,120.3062948&zoom=16&size=600x300&maptype=roadmap
or
https://maps.googleapis.com/maps/api/staticmap?markers=高雄夢時代|高雄火車站&path=高雄夢時代|高雄火車站&size=600x300&maptype=roadmap

distance

1
https://maps.googleapis.com/maps/api/distancematrix/json?origins=高雄夢時代&destinations=高雄火車站
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
回傳
{
"destination_addresses" : [ "807台灣高雄市三民區建國二路320號高雄車站" ],
"origin_addresses" : [ "806台灣高雄市前鎮區中華五路789號" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "5.7 公里",
"value" : 5652
},
"duration" : {
"text" : "17 分",
"value" : 1021
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}

完整程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Map</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<script>
const navigation = (url) => window.open(encodeURI(url), '_blank');
const getStaticMap = () => {
const destination = '高雄夢時代';
const destination_mark = `color:red|label:D|${destination}`;
const src = `https://maps.googleapis.com/maps/api/staticmap?center=${destination}&markers=${destination_mark}&zoom=16&size=600x300&maptype=roadmap`;
$('#img1').attr('src', encodeURI(src));
};
const getStaticMapNav = () => {
const position = `高雄夢時代|高雄火車站`;
const src = `https://maps.googleapis.com/maps/api/staticmap?markers=${position}&path=${position}&size=600x300&maptype=roadmap`;
$('#img2').attr('src', encodeURI(src));
};
</script>
<div>
<button onClick="navigation(`http://maps.google.com/maps?saddr=Current+Location&daddr=高雄夢時代`)">
URL1
</button>
<button onClick="navigation(`http://maps.google.com/maps?saddr=Current+Location&daddr=22.5961822,120.3062948`)">
URL2
</button>
</div>
<div>
<button onClick="getStaticMap()">
Google Static Map
</button>
<img id="img1" src="" alt="Google Static Map">
</div>
<div>
<button onClick="getStaticMapNav()">
Google Static Map Navigation
</button>
<img id="img2" src="" alt="Google Static Map Navigation">
</div>
</body>
</html>