I've created a fiddle example here where anyone can check my problem.
That problem is that when two overlays (built with a svg element and a path inside it) are too close, i.e, side by side, and both shapes have irregular limits, then the last shape rendered is overlapping the first one.
Visually you can't appreciate it, but if you add, e.g., a click event to the path dom elements to show their names, the last rendered shape is clickable in al its region, but the first one is not entirely clickable. The marked region in the following picture is not clickable for the bottom picture but it should be:
There is a css rule to change the cursor when it is over a path. You can also see that in the specified region the cursor does not change.
How can I avoid this overlapping? What I want is to do the bottom shape entirely clickable.
Finally I tried to find another solution like getting all elements under the mouse position and determine which path was, at that moment, under the pointer, and execute the action on it. I was looking for a way to implement this solution and I found this post: solution!!, where there is just what I needed.
I think it is the best and more elegant way (at least better than I thought before) to solve my issue. Basically it adds the css rule pointer-events: none; to the top svg element which is blocking other path elements. And to the pathobjects I have added pointer-events: all;. So the css styles should look like this:
svg.overlay {
pointer-events: none;
}
svg.overlay > path {
pointer-events: all;
}
The entire solution (you can see it also in a jsfiddler example):
function initialize() {
var myLatLng = new google.maps.LatLng(42, -111.02783203125);
var mapOptions = {
zoom: 6,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//polygon coords for Utah
var path = [
new google.maps.LatLng(41.983994270935625, -111.02783203125),
new google.maps.LatLng(42.00032514831621, -114.01611328125),
new google.maps.LatLng(36.96744946416931, -114.01611328125),
new google.maps.LatLng(37.00255267215955, -109.0283203125),
new google.maps.LatLng(40.97989806962013, -109.0283203125),
new google.maps.LatLng(41.0130657870063, -111.02783203125)
];
// custom overlay created
var overlay = new BW.PolyLineFill(path, map, 'red', '#000', 'original');
// polygon coords for conflict shape
var pathConflict = [
new google.maps.LatLng(42.00032514831621, -114.01611328125),
new google.maps.LatLng(41.983994270935625, -111.02783203125),
new google.maps.LatLng(41.0130657870063, -111.02783203125),
new google.maps.LatLng(40.97989806962013, -109.0283203125),
new google.maps.LatLng(47.00255267215955, -109.0283203125),
new google.maps.LatLng(46.96744946416931, -114.01611328125)
];
var overlayConflict = new BW.PolyLineFill(pathConflict, map, 'white', '#000', 'conflict');
}
///Start custom poly fill code
PolyLineFill.prototype = new google.maps.OverlayView();
function PolyLineFill(poly, map, fill, stroke, name) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < poly.length; i++) {
bounds.extend(poly[i]);
}
//initialize all properties.
this.bounds_ = bounds;
this.map_ = map;
this.$dom = null;
this.poly_ = poly;
this.polysvg_ = null;
this.fill_ = fill;
this.stroke_ = stroke;
this.name_ = name;
// Explicitly call setMap on this overlay
this.setMap(map);
}
PolyLineFill.prototype.onAdd = function() {
//createthe svg element
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(svgns, "svg");
svg.setAttributeNS(null, "preserveAspectRatio", "xMidYMid meet");
var def = document.createElementNS(svgns, "defs");
//create the pattern fill
var pattern = document.createElementNS(svgns, "pattern");
pattern.setAttributeNS(null, "id", "lineFill-" + this.name_);
pattern.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
pattern.setAttributeNS(null, "patternTransform", "rotate(-45)");
pattern.setAttributeNS(null, "height", "7");
pattern.setAttributeNS(null, "width", "7");
def.appendChild(pattern);
var rect = document.createElementNS(svgns, "rect");
rect.setAttributeNS(null, "id", "rectFill");
rect.setAttributeNS(null, "fill", this.fill_ || "red");
rect.setAttributeNS(null, "fill-opacity", "0.3");
rect.setAttributeNS(null, "stroke", this.stroke_ || "#000");
rect.setAttributeNS(null, "stroke-dasharray", "7,7");
rect.setAttributeNS(null, "height", "7");
rect.setAttributeNS(null, "width", "7");
pattern.appendChild(rect);
svg.appendChild(def);
//add path to the div
var path = document.createElementNS(svgns, 'path');
path.setAttributeNS(null, 'fill', 'url(#lineFill-' + this.name_ + ')');
path.setAttributeNS(null, 'stroke', '#000');
path.setAttributeNS(null, 'stroke-width', '1');
path.setAttributeNS(null, 'pointer-events', 'all');
this.path_ = path;
svg.appendChild(this.path_);
svg.style.borderStyle = 'none';
svg.style.borderWidth = '0px';
svg.style.position = 'absolute';
svg.style.pointerEvents = 'none';
svg.setAttribute('class', 'polygon');
this.$dom = svg;
// We add an overlay to a map via one of the map's panes.
// We'll add this overlay to the overlayLayer pane.
var panes = this.getPanes();
panes.overlayMouseTarget.appendChild(this.$dom);
var dragging = false;
google.maps.event.addDomListener(this.path_, 'mousedown', function(evt) {
dragging = false;
});
google.maps.event.addDomListener(this.path_, 'mousemove', function(evt) {
dragging = true;
});
var _self = this;
// onclick listener
google.maps.event.addDomListener(this.path_, 'click', function(evt) {
if (dragging) {
return false;
}
alert('clicked on ' + _self.name_);
});
}
PolyLineFill.prototype.AdjustPoints = function() {
//adjust the polygon points based on the projection.
var proj = this.getProjection();
var sw = proj.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = proj.fromLatLngToDivPixel(this.bounds_.getNorthEast());
var points = "";
for (var i = 0; i < this.poly_.length; i++) {
var point = proj.fromLatLngToDivPixel(this.poly_[i]);
if (i == 0) {
points += (point.x - sw.x) + ", " + (point.y - ne.y);
} else {
points += " " + (point.x - sw.x) + ", " + (point.y - ne.y);
}
}
return points;
}
PolyLineFill.prototype.draw = function() {
// Size and position the overlay. We use a southwest and northeast
// position of the overlay to peg it to the correct position and size.
// We need to retrieve the projection from this overlay to do this.
var overlayProjection = this.getProjection();
// Retrieve the southwest and northeast coordinates of this overlay
// in latlngs and convert them to pixels coordinates.
// We'll use these coordinates to resize the DIV.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's DIV to fit the indicated dimensions.
var div = this.$dom;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
this.path_.setAttributeNS(null, "d", 'M' + this.AdjustPoints() + 'z');
}
PolyLineFill.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
window.BW = {};
window.BW.PolyLineFill = PolyLineFill;
///end poly fill code
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.polygon: {
pointer-events: none;
}
.polygon > path {
cursor: pointer;
pointer-events: all;
}
.polygon > path:active {
cursor: -webkit-grabbing;
}
#map-canvas,
#map_canvas {
height: 100%;
}
#media print {
html,
body {
height: auto;
}
#map_canvas {
height: 650px;
}
}
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="map-canvas"></div>
Related
I'm trying to create a custom overlay that covers a large part of the world map (ideally the whole world - inside the overlay I want to use an SVG or canvas that would only uncover selected parts of the map). Here is an example that demonstrates my issue:
function initMap() {
const map = new google.maps.Map(
document.getElementById("map"), {
zoom: 1,
center: {
lat: 0,
lng: 0
},
}
);
const bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-20, -100),
new google.maps.LatLng(+20, 100)
);
class CustomOverlay extends google.maps.OverlayView {
bounds_
div_
constructor(bounds, image) {
super();
this.bounds_ = bounds;
this.div_ = null;
}
onAdd() {
this.div_ = document.createElement("div");
this.div_.style.width = '100%'
this.div_.style.height = '100%'
this.div_.style.position = "absolute";
this.div_.style.background = "red"
const panes = this.getPanes();
panes.overlayLayer.appendChild(this.div_);
}
draw() {
const overlayProjection = this.getProjection();
const sw = overlayProjection.fromLatLngToDivPixel(
this.bounds_.getSouthWest()
);
const ne = overlayProjection.fromLatLngToDivPixel(
this.bounds_.getNorthEast()
);
if (this.div_) {
this.div_.style.left = sw.x + "px";
this.div_.style.top = ne.y + "px";
this.div_.style.width = ne.x - sw.x + "px";
this.div_.style.height = sw.y - ne.y + "px";
}
}
onRemove() {
if (this.div_) {
(this.div_.parentNode).removeChild(this.div_);
this.div_ = null;
}
}
}
const overlay = new CustomOverlay(bounds);
overlay.setMap(map);
}
window.initMap = initMap;
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<html>
<head>
<title>Rectangle Zoom</title>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&v=weekly" defer></script>
</body>
</html>
The problem is: whenever I zoom into an area in the eastern part of the red rectangle (Sri Lanka, Malaysia) the overlay disappears.
When I zoom out and pan the map I can see that the overlay is not disappearing - it's just moving to the next "repeated copy" of the map to the east.
How can I prevent this from happening?
Here are some of my ideas, but I can't find a way to implement any of them:
Disabling map repeating (only show one world map) - restricting the scrolling area doesn't fix the problem, I've tried
Locking my overlay to the correct "copy" of the map or show it on every "copy"
Using something different than a custom overlay (a polygon or rectangle won't work because I want to put an image or custom HTML element inside the map)
EDIT: I've just posted this issue on the Google Issue Tracker - here
I need to be able to highlight features in a bounding box using Mapbox GL as shown in this example. My map also needs to have the ability to change the style layer, e.g. changing the base style from mapbox://styles/mapbox/light-v10 to mapbox://styles/mapbox/satellite-v9. This has been challenging because Mapbox GL does not natively support the concept of "basemaps" like, e.g. leaflet does.
My solution, after much searching (I believe I eventually followed a workaround posted in a github issue) involved:
Using map.on('style.load') instead of map.on('load') as shown in the example (I believe map.on('style.load') is not part of their public API, but I could be wrong) and,
Iterating through an array of sources/layers (see the vectorTileLayers variable in the code below) to add vector tiles layers to the map every time a new style is loaded.
This works brilliantly for me in some ways - I'm able to add an arbitrary number of vector tile sources to the array, and they are all added back to the map if the base style is changed. However, I am unable to add a query feature following the example provided by Mapbox if the sources/layers are added to the map in an array and iterated through as shown below. The bounding feature works, but when it is drawn, and released, I see the error show by running the snippet below.
This is a simplified version my actual problem that will allow others to run and manipulate the code. In reality, I'm adding my own vector tile layers (stored in the vectorTileLayers array, which works without issue. When I try and add another layer with the same source and different styling, as shown in the example, I'm unable to actually query the desired layer. Any help would be greatly appreciated. Just FYI - the toggleable layers buttons are not showing up in this snippet, but it's not critical to solve the problem.
mapboxgl.accessToken = 'pk.eyJ1IjoiamFtZXljc21pdGgiLCJhIjoiY2p4NTRzdTczMDA1dzRhbXBzdmFpZXV6eCJ9.-k7Um-xmYy4xhNDN6kDvpg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-98, 38.88],
minZoom: 2,
zoom: 3
});
var vectorTileLayers = [{
source: {
type: 'vector',
url: 'mapbox://mapbox.82pkq93d'
},
layer: {
id: 'counties',
type: 'fill',
source: 'counties',
'source-layer': 'original',
paint: {
'fill-outline-color': 'rgba(0,0,0,0.1)',
'fill-color': 'rgba(0,0,0,0.1)'
},
}
},
{
source: {
type: 'vector',
url: 'mapbox://mapbox.82pkq93d'
},
layer: {
id: 'counties-highlighted',
type: 'fill',
source: 'counties',
'source-layer': 'original',
paint: {
'fill-outline-color': '#484896',
'fill-color': '#6e599f',
'fill-opacity': 0.75
},
filter: ['in', 'FIPS', '']
}
}
]
map.on('style.load', function() {
for (var i = 0; i < vectorTileLayers.length; i++) {
var tileLayer = vectorTileLayers[i];
map.addSource(tileLayer.layer.source, tileLayer.source);
map.addLayer(tileLayer.layer);
}
var layerList = document.getElementById('basemapmenu');
var inputs = layerList.getElementsByTagName('input');
function switchLayer(layer) {
var layerId = layer.target.id;
map.setStyle('mapbox://styles/mapbox/' + layerId);
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
});
// Disable default box zooming.
map.boxZoom.disable();
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false
});
var canvas = map.getCanvasContainer();
var start;
var current;
var box;
canvas.addEventListener('mousedown', mouseDown, true);
// Return the xy coordinates of the mouse position
function mousePos(e) {
var rect = canvas.getBoundingClientRect();
return new mapboxgl.Point(
e.clientX - rect.left - canvas.clientLeft,
e.clientY - rect.top - canvas.clientTop
);
}
function mouseDown(e) {
// Continue the rest of the function if the shiftkey is pressed.
if (!(e.shiftKey && e.button === 0)) return;
// Disable default drag zooming when the shift key is held down.
map.dragPan.disable();
// Call functions for the following events
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
document.addEventListener('keydown', onKeyDown);
// Capture the first xy coordinates
start = mousePos(e);
}
function onMouseMove(e) {
// Capture the ongoing xy coordinates
current = mousePos(e);
// Append the box element if it doesnt exist
if (!box) {
box = document.createElement('div');
box.classList.add('boxdraw');
canvas.appendChild(box);
}
var minX = Math.min(start.x, current.x),
maxX = Math.max(start.x, current.x),
minY = Math.min(start.y, current.y),
maxY = Math.max(start.y, current.y);
// Adjust width and xy position of the box element ongoing
var pos = 'translate(' + minX + 'px,' + minY + 'px)';
box.style.transform = pos;
box.style.WebkitTransform = pos;
box.style.width = maxX - minX + 'px';
box.style.height = maxY - minY + 'px';
}
function onMouseUp(e) {
// Capture xy coordinates
finish([start, mousePos(e)]);
}
function onKeyDown(e) {
// If the ESC key is pressed
if (e.keyCode === 27) finish();
}
function finish(bbox) {
// Remove these events now that finish has been called.
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('keydown', onKeyDown);
document.removeEventListener('mouseup', onMouseUp);
if (box) {
box.parentNode.removeChild(box);
box = null;
}
// If bbox exists. use this value as the argument for `queryRenderedFeatures`
if (bbox) {
var features = map.queryRenderedFeatures(bbox, {
layers: ['counties']
});
if (features.length >= 1000) {
return window.alert('Select a smaller number of features');
}
// Run through the selected features and set a filter
// to match features with unique FIPS codes to activate
// the `counties-highlighted` layer.
var filter = features.reduce(
function(memo, feature) {
memo.push(feature.properties.FIPS);
return memo;
},
['in', 'FIPS']
);
map.setFilter('counties-highlighted', filter);
}
map.dragPan.enable();
}
map.on('mousemove', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['counties-highlighted']
});
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = features.length ? 'pointer' : '';
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
popup
.setLngLat(e.lngLat)
.setText(feature.properties.COUNTY)
.addTo(map);
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
#basemapmenu {
position: absolute;
display: inline-block;
background-color: transparent;
bottom: 0;
left: 0;
margin-left: 10px;
margin-bottom: 40px;
}
.boxdraw {
background: rgba(56, 135, 190, 0.1);
border: 2px solid #3887be;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet"/>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<div id="map"></div>
<div id='basemapmenu'>
<input id='light-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Light' checked='checked'>
<input id='dark-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Dark'>
<input id='satellite-v9' class='btn btn-outline-primary' type='button' name='rtoggle' value='Satellite'>
</div>
I ran you code locally and found the problem!
You are trying to add same source twice and mapbox was giving you error for that, if you check your Console:
Problem: There can be only one source with one ID on Map
Error: There is already a source with this ID
After first loop execute successfully. On second iteration, it fails to add same source twice, code breaks here and doesn't continue further. Hence doesn't add second layer(therefore no functionality works thereafter!)
Fix:(Added a small check to not add same source if already added)
map.on('style.load', function () {
for (var i = 0; i < vectorTileLayers.length; i++) {
var tileLayer = vectorTileLayers[i];
if (!map.getSource(tileLayer.layer.source,)) //FIX
map.addSource(tileLayer.layer.source, tileLayer.source);
map.addLayer(tileLayer.layer);
}
var layerList = document.getElementById('basemapmenu');
var inputs = layerList.getElementsByTagName('input');
function switchLayer(layer) {
var layerId = layer.target.id;
map.setStyle('mapbox://styles/mapbox/' + layerId);
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
});
I can see the Code is working fine:
Hope this will fix the problem.
I'll leave the above answer from Dolly as accepted because it answers my original question exactly. Unforunately, it didn't exactly solve my actual problem. After some additional fiddling, I wanted to post a fully functional version for reference in case people come across this looking for a solution to adding toggleable "basemap" layers in Mapbox GL with or without user interactivity options like this one.
The solution above does not work after toggling between basemap layers. The vector tile layers are not reloaded properly. The solution below seems to do the trick. It uses map.on('styledata' ...) rather than map.on('style.load' ...), which seems to allow for loading layers by the more conventional method of first calling map.addSource() followed by map.addLayer(). You can load a single source, and then an arbitrary number of layers pointing to that source. So in my "real world" example, I load 3 sources, and 5 layers from those sources.
(FYI - for some reason the built-in snippet tool from stack overflow isn't rendering the basemap buttons. If you copy the code exactly into JS fiddle or codepen it will work)
I hope this helps future humans - it seems like lots of people have had problems with managing Mapbox styles with custom layers on top. I certainly have.
mapboxgl.accessToken =
"pk.eyJ1IjoiamFtZXljc21pdGgiLCJhIjoiY2p4NTRzdTczMDA1dzRhbXBzdmFpZXV6eCJ9.-k7Um-xmYy4xhNDN6kDvpg";
var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/light-v10",
center: [-98, 38.88],
minZoom: 2,
zoom: 3
});
map.on("styledata", function() {
map.addSource("counties", {
type: "vector",
url: "mapbox://mapbox.82pkq93d"
});
map.addLayer({
id: "counties",
type: "fill",
source: "counties",
"source-layer": "original",
paint: {
"fill-outline-color": "rgba(0,0,0,0.1)",
"fill-color": "rgba(0,0,0,0.1)"
}
});
map.addLayer({
id: "counties-highlighted",
type: "fill",
source: "counties",
"source-layer": "original",
paint: {
"fill-outline-color": "#484896",
"fill-color": "#6e599f",
"fill-opacity": 0.75
},
filter: ["in", "FIPS", ""]
});
var layerList = document.getElementById("basemapmenu");
var inputs = layerList.getElementsByTagName("input");
function switchLayer(layer) {
var layerId = layer.target.id;
map.setStyle("mapbox://styles/mapbox/" + layerId);
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
});
// Disable default box zooming.
map.boxZoom.disable();
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false
});
var canvas = map.getCanvasContainer();
var start;
var current;
var box;
canvas.addEventListener("mousedown", mouseDown, true);
// Return the xy coordinates of the mouse position
function mousePos(e) {
var rect = canvas.getBoundingClientRect();
return new mapboxgl.Point(
e.clientX - rect.left - canvas.clientLeft,
e.clientY - rect.top - canvas.clientTop
);
}
function mouseDown(e) {
// Continue the rest of the function if the shiftkey is pressed.
if (!(e.shiftKey && e.button === 0)) return;
// Disable default drag zooming when the shift key is held down.
map.dragPan.disable();
// Call functions for the following events
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
document.addEventListener("keydown", onKeyDown);
// Capture the first xy coordinates
start = mousePos(e);
}
function onMouseMove(e) {
// Capture the ongoing xy coordinates
current = mousePos(e);
// Append the box element if it doesnt exist
if (!box) {
box = document.createElement("div");
box.classList.add("boxdraw");
canvas.appendChild(box);
}
var minX = Math.min(start.x, current.x),
maxX = Math.max(start.x, current.x),
minY = Math.min(start.y, current.y),
maxY = Math.max(start.y, current.y);
// Adjust width and xy position of the box element ongoing
var pos = "translate(" + minX + "px," + minY + "px)";
box.style.transform = pos;
box.style.WebkitTransform = pos;
box.style.width = maxX - minX + "px";
box.style.height = maxY - minY + "px";
}
function onMouseUp(e) {
// Capture xy coordinates
finish([start, mousePos(e)]);
}
function onKeyDown(e) {
// If the ESC key is pressed
if (e.keyCode === 27) finish();
}
function finish(bbox) {
// Remove these events now that finish has been called.
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener("mouseup", onMouseUp);
if (box) {
box.parentNode.removeChild(box);
box = null;
}
// If bbox exists. use this value as the argument for `queryRenderedFeatures`
if (bbox) {
var features = map.queryRenderedFeatures(bbox, {
layers: ["counties"]
});
if (features.length >= 1000) {
return window.alert("Select a smaller number of features");
}
// Run through the selected features and set a filter
// to match features with unique FIPS codes to activate
// the `counties-highlighted` layer.
var filter = features.reduce(
function(memo, feature) {
memo.push(feature.properties.FIPS);
return memo;
}, ["in", "FIPS"]
);
map.setFilter("counties-highlighted", filter);
}
map.dragPan.enable();
}
map.on("mousemove", function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ["counties-highlighted"]
});
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = features.length ? "pointer" : "";
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
popup.setLngLat(e.lngLat).setText(feature.properties.COUNTY).addTo(map);
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
#basemapmenu {
position: absolute;
display: inline-block;
background-color: transparent;
bottom: 0;
left: 0;
margin-left: 10px;
margin-bottom: 40px;
}
.boxdraw {
background: rgba(56, 135, 190, 0.1);
border: 2px solid #3887be;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<div id="map"></div>
<div id='basemapmenu'>
<input id='light-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Light' checked='checked'>
<input id='dark-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Dark'>
<input id='satellite-v9' class='btn btn-outline-primary' type='button' name='rtoggle' value='Satellite'>
</div>
I'm trying to replace markers on a Google map using the custom overlay in order to have HTML for each marker. It works except I can't figure out how to have the bottom of the overlay over the point, instead of having the top of the overlay below the point. I've reproduced the error using a super-reduced set of code just for testing (below). Instead of my actual HTML I'm just drawing a red rectangle.
The problem is in the draw function. When I assign div.style.top to the point it works (but not the way I want), but when I switch it to div.style.bottom getting the y value instead it does not work as expected; the red square is not on the map. (In my original program the markers end up being drawn in a vertically-mirrored pattern, and far from the indended locations.)
How can I get assigning div.style.bottom to work the way I want it to?
<!DOCTYPE html>
<html>
<head>
<title>Custom Overlay Test</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
var overlay;
TestOverlay.prototype = new google.maps.OverlayView();
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(38.89, -77.03)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
overlay = new TestOverlay(new google.maps.LatLng(38.89, -77.03), map);
}
function TestOverlay(point, map) {
this.point_ = point;
this.map_ = map;
this.div_ = null;
this.setMap(map);
}
TestOverlay.prototype.onAdd = function() {
var div = document.createElement('div');
div.style.borderStyle = 'solid';
div.style.borderWidth = '5px';
div.style.borderColor = '#ff0000';
div.style.position = 'absolute';
div.style.width = '200px';
div.style.height = '50px';
this.div_ = div;
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
TestOverlay.prototype.draw = function() {
var overlayProjection = this.getProjection();
var point = overlayProjection.fromLatLngToDivPixel(this.point_);
var div = this.div_;
div.style.left = point.x + 'px';
div.style.bottom = point.y + 'px';
};
TestOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Ta-da; got it. The trick is that top and bottom differ by more than whether they position the element using its top or bottom; they differ in the direction of the measurement. Both measure from the top of the parent element, but top adds to the y-axis, and bottom subtracts from the y-axis. So to fix the problem I just needed to reverse the sign of the distance: div.style.bottom = -point.y + 'px';
I am having some difficulties where my listeners appear to cancel each other out only when I set a rectangle to the map, but not when I call an alert or anything else.
This works perfectly:
google.maps.event.addDomListener(document.getElementById("overlay" + me), 'click', function () {
displayMessage(me); //displays the current overlay index on screen (IE 1 of 30)
});
The above simply displays the index of the overlay on the map (IE 1 of 30). It works at every overlay clicked with the proper overlay index.
This not so much:
google.maps.event.addDomListener(document.getElementById("overlay" + me), 'click', function () {
alert("Called");
curOverlayRectangle.setOptions(overlayRectangleOptions); //defined by C# to js
curOverlayRectangle.setBounds(incomingOverlayBounds[me]);
curOverlayRectangle.setMap(map);
alert("Finished");
});
The above is supposed to add a rectangle over the overlay already on the map. What it actually does is add the rectangle for the first overlay clicked, but then if I click another overlay, nothing happens.
It appears that the listener is never called because once I click the first overlay, it goes through and says finished with the rectangle drawn. I then proceed to click another overlay and no alert occurs...
I have been working on this for quite some time, please help! Thanks!
EDIT1:
//get is simply the index
function tempAddListener(get) {
//alert("adding: " + get);
if (document.getElementById("overlay" + get) != null) { //check to see if div is there
google.maps.event.addDomListener(document.getElementById("overlay" + get), 'click', function () {
displayMessage("listener fired at overlay: " + get); //if enabled, works fine
//displayOverlayRectangle(incomingOverlayBounds[get]); //if enabled, listener fires but seems to delete all my other listeners for the overlays
});
} else {
//could not find the div
}
}
Edit2
//took out all defines
//#region geoObjs
var incomingOverlayBounds = [];
var incomingOverlaySourceURL = [];
var incomingOverlayRotation = [];
var incomingOverlayRectangle = [];
function initOverlays(){
//most of these are taken out
incomingOverlayBounds[0] = new google.maps.LatLngBounds( new google.maps.LatLng(29.7883456702236,-82.384843759249), new
incomingOverlayRotation[16] = 0;
incomingOverlayBounds[17] = new google.maps.LatLngBounds( new google.maps.LatLng(29.4715356702236,-82.3839748493845), new google.maps.LatLng(29.51265,-82.33674));
incomingOverlaySourceURL[17] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_20.jpg";
incomingOverlayRotation[17] = 0;
incomingOverlayBounds[18] = new google.maps.LatLngBounds( new google.maps.LatLng(29.4584356702236,-82.3840587432067), new google.maps.LatLng(29.49955,-82.33683));
incomingOverlaySourceURL[18] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_21.jpg";
incomingOverlayRotation[18] = 0;
incomingOverlayBounds[19] = new google.maps.LatLngBounds( new google.maps.LatLng(29.4431556702236,-82.4158516259991), new google.maps.LatLng(29.48427,-82.36863));
incomingOverlaySourceURL[19] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_022.jpg";
incomingOverlayRotation[19] = 0;
incomingOverlayBounds[20] = new google.maps.LatLngBounds( new google.maps.LatLng(29.4593656702236,-82.4157191765652), new google.maps.LatLng(29.50048,-82.36849));
incomingOverlaySourceURL[20] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_023.jpg";
incomingOverlayRotation[20] = 0;
incomingOverlayBounds[21] = new google.maps.LatLngBounds( new google.maps.LatLng(29.4736856702236,-82.4151858519302), new google.maps.LatLng(29.5148,-82.36795));
incomingOverlaySourceURL[21] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_024.jpg";
incomingOverlayRotation[21] = 0;
incomingOverlaySourceURL[51] = "http://ufdcimages.uflib.ufl.edu/UF/00/07/17/26/00027/12001_1968_2KK_054.jpg";
incomingOverlayRotation[51] = 0;
displayIncomingOverlays();
}
//#endregion
function initialize() {
//initialize google map objects
map = new google.maps.Map(document.getElementById(gmapPageDivId), gmapOptions); //initialize map
initOverlays(); //initialize all the incoming overlays
}
var incomingOverlayBounds = [];
var incomingOverlaySourceURL = [];
var incomingOverlayRotation = [];
var overlays = [];
function displayIncomingOverlays() {
for (var i = 0; i < incomingOverlayBounds.length; i++) {
overlaysOnMap[i] = new CustomOverlay(incomingOverlayBounds[i], incomingOverlaySourceURL[i], map, incomingOverlaySourceURL[i]);
overlaysOnMap[i].setMap(map);
//displayOverlayRectangle(incomingOverlayBounds[i]); //add all the rectangles
}
}
function CustomOverlay(bounds, image, map, rotation) {
//iterate here
overlayCount++;
// Now initialize all properties.
this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;
preservedRotation = rotation;
if (overlayPrevious != null) {
overlayPrevious.setMap(null);
}
// We define a property to hold the image's div. We'll
// actually create this div upon receipt of the onAdd()
// method so we'll leave it null for now.
this.div_ = null;
}
CustomOverlay.prototype.onAdd = function () {
if (overlayPrevious != null) {
overlayPrevious.setMap(null);
}
// Note: an overlay's receipt of onAdd() indicates that
// the map's panes are now available for attaching
// the overlay to the map via the DOM.
// Create the DIV and set some basic attributes.
var div = document.createElement("div");
div.id = "overlay" + overlaysOnMap.indexOf(this);
div.style.borderStyle = 'none';
div.style.borderWidth = '0px';
div.style.position = 'absolute';
div.style.opacity = preserveOpacity;
// Create an IMG element and attach it to the DIV.
var img = document.createElement('img');
img.src = incomingOverlaySourceURL[overlaysOnMap.indexOf(this)]; //this.image
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'absolute';
div.appendChild(img);
//get the index
var overlayIndex = overlaysOnMap.indexOf(this);
// Set the overlay's div_ property to this DIV
this.div_ = div;
// We add an overlay to a map via one of the map's panes.
// We'll add this overlay to the overlayLayer pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
//add the listener
tempAddListener(overlayIndex);
};
CustomOverlay.prototype.draw = function () {
// Size and position the overlay. We use a southwest and northeast
// position of the overlay to peg it to the correct position and size.
// We need to retrieve the projection from this overlay to do this.
var overlayProjection = this.getProjection();
// Retrieve the southwest and northeast coordinates of this overlay
// in latlngs and convert them to pixels coordinates.
// We'll use these coordinates to resize the DIV.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's DIV to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
//for a preserved rotation
if (preservedRotation != 0) {
//keepRotate(preservedRotation);
}
};
//CustomOverlay.prototype.onRemove = function () {
// this.div_.parentNode.removeChild(this.div_);
// this.div_ = null;
//};
function tempAddListener(get) {
alert("div: "+document.getElementById("overlay" + get).innerHTML);
alert("adding with index: " + get);
if (document.getElementById("overlay" + get) != null) { //check to see if div is there
google.maps.event.addDomListener(document.getElementById("overlay" + get), 'click', function () {
alert("listener fired at overlay: " + get);
displayOverlayRectangle(incomingOverlayBounds[get]);
//alert(incomingOverlayBounds[get]);
//overlayRectangles[get] = displayOverlayRectangle(incomingOverlayBounds[get]);
//overlayRectangles[get].setMap(map);
});
} else {
//could not find the div
}
}
function displayOverlayRectangle(bounds) {
//2do: set drawing manager, set mode, match listeners of rectangle
var tempOverlayRectangle = new google.maps.Rectangle();
var tempOverlayRectangleOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.1,
editable: true,
draggable: true,
//strokeOpacity: 0.2,
//strokeWeight: 1,
//fillOpacity: 0.0,
zindex: 5
};
tempOverlayRectangle.setOptions(tempOverlayRectangleOptions);
tempOverlayRectangle.setBounds(bounds);
tempOverlayRectangle.setMap(map);
google.maps.event.addListener(tempOverlayRectangle, "click", function () {
alert("can't touch this");
});
//return tempOverlayRectangle;
//tempOverlayRectangle.setOptions(tempOverlayRectangleOptions);
//tempOverlayRectangle.setBounds(bounds);
//tempOverlayRectangle.setMap(map);
}
//start this whole mess once
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="googleMap"></div>
UPDATE
It appears that any map code on the listener will invalidate the other listeners. (IE I tried it with the following code and it still only ran once)
google.maps.event.addDomListener(document.getElementById("overlay" + get), 'click', function () {
if (map.getMapTypeId() == 'TERRAIN') {
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
} else {
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
}
});
SOLVED
Bottom line, the overlay I was creating could not be accessed appropriately by the DOM. Thus, I created an invisible rectangle to overlay on top of my overlay which can be accessed.
Snippet:
var incomingOverlayBounds = []; //defined in c# to js on page
var incomingOverlaySourceURL = []; //defined in c# to js on page
var incomingOverlayRotation = []; //defined in c# to js on page
var ghostOverlayRectangle = []; //holds ghost overlay rectangles (IE overlay hotspots)
var ghostOverlayRectangleOptions = { //define options for ghost rectangle
strokeColor: "#FF0000", //color doesnt matter
strokeOpacity: 0.0, //make border invisible
strokeWeight: 1, //should not matter?
fillColor: "#FF0000", //color doesnt matter
fillOpacity: 0.0, //make fill transparent
editable: false, //just to be sure?
draggable: false, //just to be sure?
zindex: 6 //perhaps higher?
};
var visibleOverlayRectangleOptions = { //define options for visible rectangle
strokeColor: "#FF0000", //for testing (red)
strokeOpacity: 0.8, //for testing
strokeWeight: 2, //for testing
fillColor: "#FF0000", //for testing (red)
fillOpacity: 0.1, //for testing
editable: true, //sobek standard
draggable: true, //sobek standard
//strokeOpacity: 0.2, //sobek standard
//strokeWeight: 1, //sobek standard
//fillOpacity: 0.0, //sobek standard
zindex: 5 //sobek standard
};
var visibleOverlayRectangle = new google.maps.Rectangle(); //init maybe move to array later
//Displays all the overlays sent from the C# code. Also calls displayGhostOverlayRectangle.
function displayIncomingOverlays() {
//go through and display overlays as long as there is an overlay to display
for (var i = 0; i < incomingOverlayBounds.length; i++) {
overlaysOnMap[i] = new CustomOverlay(incomingOverlayBounds[i], incomingOverlaySourceURL[i], map, incomingOverlayRotation[i]);
overlaysOnMap[i].setMap(map); //set the overlay to the map
displayGhostOverlayRectangle(incomingOverlayBounds[i],i); //add all the ghost rectangles
}
}
//Displays an invisible rectangle on top of the overlay div (creates a hotspot). This rectangle is used as a psuedo listener if the 'overlay div' is clicked. This solved issue of creating listener for overlay div directly.
//Supporting URL: http://stackoverflow.com/questions/17025240/google-maps-listener-only-running-once
function displayGhostOverlayRectangle(ghostBounds,ghostIndex) {
ghostOverlayRectangle[ghostIndex] = new google.maps.Rectangle(); //init rect
ghostOverlayRectangle[ghostIndex].setOptions(ghostOverlayRectangleOptions); //set options
ghostOverlayRectangle[ghostIndex].setBounds(ghostBounds); //set bounds
ghostOverlayRectangle[ghostIndex].setMap(map); //set to map
//create the listener for this ghost rectangle
google.maps.event.addListener(ghostOverlayRectangle[ghostIndex], 'click', function () {
displayVisibleOverlayRectangle(ghostBounds, ghostIndex); //add the visible rectangles
});
}
//Displays the visible rectangle which is used to edit an overlay. Called by the ghost listener.
function displayVisibleOverlayRectangle(bounds, overlayIndex) {
visibleOverlayRectangle.setOptions(visibleOverlayRectangleOptions);
visibleOverlayRectangle.setBounds(bounds);
visibleOverlayRectangle.setMap(map);
}
//Starts the creation of a custom overlay div which contains a rectangular image.
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays
function CustomOverlay(bounds, image, map, rotation) {
overlayCount++; //iterate how many overlays have been drawn
this.bounds_ = bounds; //set the bounds
this.image_ = image; //set source url
this.map_ = map; //set to map
preservedRotation = rotation; //set the rotation
this.div_ = null; //defines a property to hold the image's div. We'll actually create this div upon receipt of the onAdd() method so we'll leave it null for now.
}
//Continues support for adding an custom overlay
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays
// Note: an overlay's receipt of onAdd() indicates that the map's panes are now available for attaching the overlay to the map via the DOM.
CustomOverlay.prototype.onAdd = function () {
// Create the DIV and set some basic attributes.
var div = document.createElement("div");
div.id = "overlay" + overlaysOnMap.indexOf(this);
div.style.borderStyle = 'none';
div.style.borderWidth = '0px';
div.style.position = 'absolute';
div.style.opacity = preserveOpacity;
// Create an IMG element and attach it to the DIV.
var img = document.createElement('img');
img.src = incomingOverlaySourceURL[overlaysOnMap.indexOf(this)]; //this.image
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'absolute';
div.appendChild(img);
// Set the overlay's div_ property to this DIV
this.div_ = div;
// We add an overlay to a map via one of the map's panes.
// We'll add this overlay to the overlayLayer pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
//Continues support for adding an custom overlay
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays
CustomOverlay.prototype.draw = function () {
// Size and position the overlay. We use a southwest and northeast
// position of the overlay to peg it to the correct position and size.
// We need to retrieve the projection from this overlay to do this.
var overlayProjection = this.getProjection();
// Retrieve the southwest and northeast coordinates of this overlay
// in latlngs and convert them to pixels coordinates.
// We'll use these coordinates to resize the DIV.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's DIV to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
//for a preserved rotation
if (preservedRotation != 0) {
keepRotate(preservedRotation);
}
};
//Not currently used
//Supporting URL: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays
CustomOverlay.prototype.onRemove = function () {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
I'm working with a Google Maps example code , this : http://www.wolfpil.de/v3/drag-from-outside.html which has 3 draggable markers outside the map. All I want is to use the revert 'invalid' option to make the markers return to the original position in case the markers do not drop in the map but I've failed to put it in the right line. Could you please give me a hint where do I have to put it to make it work?
function initDrag(e) {
if(!e) var e = window.event;
// Drag image's parent div element
obj = e.target ? e.target.parentNode : e.srcElement.parentElement;
if(obj.className != "drag") {
if(e.cancelable) e.preventDefault();
obj = null;
return;
}
if (obj) {
// The currently dragged object always gets the highest z-index
z_index++;
obj.style.zIndex = z_index.toString();
xpos = e.clientX - obj.offsetLeft;
ypos = e.clientY - obj.offsetTop;
document.onmousemove = moveObj;
}
return false;
}
function moveObj(e) {
if(obj && obj.className == "drag") {
if(!e) var e = window.event;
obj.style.left = e.clientX - xpos + "px";
obj.style.top = e.clientY - ypos + "px";
obj.onmouseup = function() {
var gd = map.getDiv();
var mLeft = gd.offsetLeft;
var mTop = gd.offsetTop;
var mWidth = gd.offsetWidth;
var mHeight = gd.offsetHeight;
var areaLeft = drag_area.offsetLeft;
var areaTop = drag_area.offsetTop;
var oWidth = obj.offsetWidth;
var oHeight = obj.offsetHeight;
// The object's pixel position relative to the document
var x = obj.offsetLeft + areaLeft + oWidth/2;
var y = obj.offsetTop + areaTop + oHeight/2;
// Check if the cursor is inside the map div
if (x > mLeft && x < (mLeft + mWidth) && y > mTop && y < (mTop + mHeight)) {
// Difference between the x property of iconAnchor
// and the middle of the icon width
var anchorDiff = 1;
// Find the object's pixel position in the map container
var g = google.maps;
var pixelpoint = new g.Point(x - mLeft -anchorDiff, y - mTop + (oHeight/2));
// Corresponding geo point on the map
var proj = dummy.getProjection();
var latlng = proj.fromContainerPixelToLatLng(pixelpoint);
// Create a corresponding marker on the map
var src = obj.firstChild.getAttribute("src");
createDraggedMarker(latlng, src);
// Create dragged marker anew
fillMarker();
}
};
}
return false;
}
function fillMarker() {
var m = document.createElement("div");
m.style.position = "absolute";
m.style.width = "32px";
m.style.height = "32px";
var left;
if (obj.id == "m1") {
left = "0px";
} else if (obj.id == "m2") {
left = "50px";
} else if (obj.id == "m3") {
left = "100px";
}
m.style.left = left;
// Set the same id and class attributes again
// m.setAttribute("id", obj.id);
// m.setAttribute((document.all?"className":"class"), "drag");
m.id = obj.id;
m.className = "drag";
// Append icon
var img = document.createElement("img");
img.src = obj.firstChild.getAttribute("src");
img.style.width = "32px";
img.style.height = "32px";
m.appendChild(img);
drag_area.replaceChild(m, obj);
// Clear initial object
obj = null;
}
function highestOrder() {
/**
* The currently dragged marker on the map
* always gets the highest z-index too
*/
return z_index;
}
function createDraggedMarker(point, src) {
var g = google.maps;
var image = new g.MarkerImage(src,
new g.Size(32, 32),
new g.Point(0, 0),
new g.Point(15, 32));
var shadow = new g.MarkerImage("http://maps.gstatic.com/mapfiles/kml/paddle/A_maps.shadow.png",
new g.Size(59, 32),
new g.Point(0, 0),
new g.Point(15, 32));
var marker = new g.Marker({ position: point, map: map,
clickable: true, draggable: true,
raiseOnDrag: false,
icon: image, shadow: shadow, zIndex: highestOrder()
});
g.event.addListener(marker, "click", function() {
actual = marker;
var lat = actual.getPosition().lat();
var lng = actual.getPosition().lng();
iw.setContent(lat.toFixed(6) + ", " + lng.toFixed(6));
iw.open(map, this);
});
g.event.addListener(marker, "dragstart", function() {
// Close infowindow when dragging the marker whose infowindow is open
if (actual == marker) iw.close();
// Increment z_index
z_index++;
marker.setZIndex(highestOrder());
});
}
After the code snippet
fillMarker();
}
add an else statement like this:
fillMarker();
} else {
//if the marker does not land on the map reset marker location
var left;
if (obj.id == "m1") {
left = "0px";
} else if (obj.id == "m2") {
left = "50px";
} else if (obj.id == "m3") {
left = "100px";
}
obj.style.left = left;
obj.style.top = "70px";
}
jsFiddle to full code: http://jsfiddle.net/6ECVs/