|
(function() { |
|
"use strict"; |
|
//console.clear(); |
|
|
|
/** |
|
Our custom overlay class, based on this example: |
|
http://serversideguy.com/2017/10/31/how-do-i-place-svgs-on-a-google-map-using-custom-overlays/ |
|
|
|
More info: |
|
https://developers.google.com/maps/documentation/javascript/customoverlays |
|
*/ |
|
class SVGOverlay extends google.maps.OverlayView { |
|
|
|
constructor(bounds, svg, map) { |
|
super(); |
|
|
|
this.bounds = bounds; |
|
this.svg = svg; |
|
|
|
super.setMap(map); |
|
} |
|
|
|
/** |
|
Will be called when the map is ready for the overlay to be attached. |
|
*/ |
|
onAdd() { |
|
const svg = this.svg; |
|
svg.style.position = 'absolute'; |
|
|
|
//Add the SVG element to a map pane/layer that is able to receive mouse events: |
|
const panes = super.getPanes(); |
|
panes.overlayMouseTarget.appendChild(svg); |
|
} |
|
|
|
/** |
|
Whenever we need to (re)draw the overlay on the map, including when first added. |
|
*/ |
|
draw() { |
|
//Here, we need to find the correct on-screen position for our image. |
|
//To achieve that, we simply ask the map's projection to calculate viewport pixels from the image's lat/lng bounds: |
|
const projection = super.getProjection(), |
|
bounds = this.bounds, |
|
sw = projection.fromLatLngToDivPixel(bounds.getSouthWest()), |
|
ne = projection.fromLatLngToDivPixel(bounds.getNorthEast()); |
|
|
|
//Place/resize the SVG element: |
|
const s = this.svg.style; |
|
s.left = sw.x + 'px'; |
|
s.top = ne.y + 'px'; |
|
s.width = (ne.x - sw.x) + 'px'; |
|
s.height = (sw.y - ne.y) + 'px'; |
|
} |
|
|
|
} //SVGOverlay |
|
|
|
|
|
|
|
function addEvent(target, type, handler) { |
|
const targets = (typeof target === 'string') ? Array.from(document.querySelectorAll(target)) |
|
: [target]; |
|
targets.forEach(t => google.maps.event.addDomListener(t, type, handler)); |
|
} |
|
|
|
function initMap() { |
|
const map = new google.maps.Map(document.getElementById('map')), |
|
mySVG = document.querySelector('#svg1'); |
|
|
|
//Say which area we want the image to occupy: |
|
const svgBounds = new google.maps.LatLngBounds( |
|
new google.maps.LatLng(62.281819, -150.287132), |
|
new google.maps.LatLng(62.400471, -150.005608), |
|
); |
|
new SVGOverlay(svgBounds, mySVG, map); |
|
|
|
//For convenience, zoom in on that area: |
|
map.setCenter(svgBounds.getCenter()); |
|
map.fitBounds(svgBounds); |
|
|
|
//Handle normal DOM events on the SVG element(s): |
|
addEvent('path', 'click', e => { |
|
console.log('Clicked!'); |
|
e.currentTarget.style.fill = '#' + Math.floor(Math.random() * 0xfffff); |
|
}); |
|
addEvent('path', 'dblclick', e => { |
|
//Avoid zooming here: |
|
e.stopPropagation(); |
|
}); |
|
} |
|
|
|
addEvent(window, 'load', initMap); |
|
})(); |