Google Maps API - 自訂標記

 

了解如何在 Google 地圖上建立圖例。 圖例通常描述地圖上的符號與標記。 您可以使用自訂控制項的定位功能建立它們。

<!DOCTYPE html>
<html>
<head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
        #map {
            width: 500px;
            height: 380px;
        }
        #legend {
            font-family: Arial, sans-serif;
            background: #fff;
            padding: 10px;
            margin: 10px;
            border: 3px solid #000;
        }
            #legend h3 {
                margin-top: 0;
            }
            #legend img {
                vertical-align: middle;
            }
    </style>
</head>
<body>
    <div id="map"></div>
    <div id="legend"><h3>Legend</h3></div>
    <script>
        function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
                center: { lat: 24.930776, lng: 121.283172 },
                zoom: 15
            });
            var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
            var icons = {
                parking: {
                    name: 'Parking',
                    icon: iconBase + 'parking_lot_maps.png'
                },
                library: {
                    name: 'Library',
                    icon: iconBase + 'library_maps.png'
                },
                info: {
                    name: 'Info',
                    icon: iconBase + 'info-i_maps.png'
                }
            };
            var features = [
                {
                    position: new google.maps.LatLng(24.930000, 121.280000),
                    type: 'info'
                }, {
                    position: new google.maps.LatLng(24.935000, 121.285000),
                    type: 'parking'
                }, {
                    position: new google.maps.LatLng(24.932000, 121.282000),
                    type: 'library'
                }
            ];
            // Create markers.
            features.forEach(function (feature) {
                var marker = new google.maps.Marker({
                    position: feature.position,
                    icon: icons[feature.type].icon,
                    map: map
                });
            });
            var legend = document.getElementById('legend');
            for (var key in icons) {
                var type = icons[key];
                var name = type.name;
                var icon = type.icon;
                var div = document.createElement('div');
                div.innerHTML = '<img src="' + icon + '"> ' + name;
                legend.appendChild(div);
            }
            map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
        }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script>
</body>
</html>

 

參考資料:

控制項定位