當串接 Google Map 的 API 時,若要在一張地圖上顯示多個標記點的話,可以結合 Geocoder 和 Google Map 的 Code 來達成。
程式碼
邏輯是抓取網頁上的地址資料,然後運用 Geocoder 把地址輸入轉換成經緯度座標,然後代入 Google Map。最後就可以將多個地標呈現在同一張地圖上。使用前,請先申請 Google API Key(每天上限25000次存取),才能正常抓取資料並顯示。
前端HTML是採用 express handlebars 和 Bootstrap
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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
// HTML 部分 <div class="col-md-12"> <div id="map_wrapper"> <div id="map_canvas" class="mapping"></div> </div> </div> <br /> <div class="row"> {{#each branches}} <div class="address card border-0"> <div class="card-body"> <h5 class="card-title" id="a{{this.id}}">{{this.name}}門市</h5> <p class="text-center" id="b{{this.id}}">{{this.address}}</p> </div> </div> {{/each}} </div> // jQuery 部分 jQuery(function ($) { // Asynchronously Load the map API var script = document.createElement('script'); script.src = "https://maps.googleapis.com/maps/api/js?key={{YOUR API KEY}}&callback=initialize"; document.body.appendChild(script); }); function initialize() { var map; var geocoder = new google.maps.Geocoder(); var bounds = new google.maps.LatLngBounds(); var mapOptions = { mapTypeId: 'roadmap' }; // Display a map on the page map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); map.setTilt(45); // Multiple Markers let markers = [] let addresses = $('.card-body .text-center').map(function () { return $.trim($(this).text()) }).get() let places = $('.card-body .card-title').map(function () { return $.trim($(this).text()) }).get() for (let i = 0; i < $('.card-title').length; i++) { geocoder.geocode({ 'address': addresses[i] }, function (results, status) { if (status == 'OK') { let item = [places[i], results[0].geometry.location.lat(), results[0].geometry.location.lng()] markers.push(item) // Display multiple markers on a map // Loop through our array of markers & place each one on the map for (let i = 0; i < markers.length; i++) { var position = new google.maps.LatLng(markers[i][1], markers[i][2]); bounds.extend(position); marker = new google.maps.Marker({ position: position, map: map, title: markers[i][0] }); // Automatically center the map fitting all markers on the screen map.fitBounds(bounds); } // Override our map zoom level once our fitBounds function runs (Make sure it only runs once) var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) { this.setZoom(12); google.maps.event.removeListener(boundsListener); }); } else { console.log(status); } }) } } |
參考資料
1. Placing multiple markers on a Google Map (Using API 3)
按讚加入粉絲團