How to remove the mapbox marker - javascript

I have a function called draw() . I pass in the array value inside draw() to plot my desired marker on the map and its working well!!
function draw(j){
//for (let j =0; j< countvalue[0]; j++){
array[j].features.forEach(function (marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage =
'url(https:gin/images/pin.png)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.style.backgroundSize = '100%';
// make a marker for each feature and add it to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(
new mapboxgl.Popup({ offset: 25 }) // add popups
.setHTML('</h3><p>' + marker.properties.description + '</p>' )
)
.addTo(map);
});
}
My Question:
How will i call the draw() function to remove the marker? Pardon me if this is not possible. Thanks a lot for your time

Create a list of markers that are being added to the map and pass a value to clear all existing markers when required.
let markersList = []
function draw(j, clearAll){
if(clearAll){
if(markersList){
for (var i = markersList.length - 1; i >= 0; i--) {
markersList[i].remove();
}
}
}
//for (let j =0; j< countvalue[0]; j++){
array[j].features.forEach(function (marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage =
'url(https:gin/images/pin.png)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.style.backgroundSize = '100%';
// make a marker for each feature and add it to the map
const newMarker = new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(
new mapboxgl.Popup({ offset: 25 }) // add popups
.setHTML('</h3><p>' + marker.properties.description + '</p>' )
)
.addTo(map);
markersList.push(newMarker);
});
}

Related

zoom out when infoBox is closed and only one info box open at a time Google Map

Question One: When closing an "infobox" how can I make it maps zoom back out?
Question Two: How would I make it so that only one "infobox" is open at a time?
I have tried adding:
google.maps.event.addListener(map, 'zoom_changed', function(){
if (! markers.length) { return; }
for (i in markers) {
markers[i].infoBox.close();
}
});
However the code dose not seem to work. Any thoughts?
function InfoBox(opts) {
google.maps.OverlayView.call(this);
this.latlng_ = opts.latlng;
this.map_ = opts.map;
this.content = opts.content;
this.offsetVertical_ = -195;
this.offsetHorizontal_ = 5;
this.height_ = 165;
this.width_ = 266;
var me = this;
this.boundsChangedListener_ =
google.maps.event.addListener(this.map_, "bounds_changed", function () {
return me.panMap.apply(me);
});
this.setMap(this.map_);
}
InfoBox.prototype = new google.maps.OverlayView();
InfoBox.prototype.remove = function () {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
this.createElement();
if (!this.div_) return;
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
if (!pixPosition) return;
this.div_.style.width = this.width_ + "px";
this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
this.div_.style.height = this.height_ + "px";
this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
this.div_.style.display = 'block';
};
InfoBox.prototype.createElement = function () {
var panes = this.getPanes();
var div = this.div_;
if (!div) {
div = this.div_ = document.createElement("div");
div.className = "infobox"
var contentDiv = document.createElement("div");
contentDiv.className = "content"
contentDiv.innerHTML = this.content;
var closeBox = document.createElement("div");
closeBox.className = "close";
closeBox.innerHTML = "x";
div.appendChild(closeBox);
function removeInfoBox(ib) {
return function () {
ib.setMap(null);
};
}
google.maps.event.addDomListener(closeBox, 'click', removeInfoBox(this));
div.appendChild(contentDiv);
div.style.display = 'none';
panes.floatPane.appendChild(div);
this.panMap();
} else if (div.parentNode != panes.floatPane) {
div.parentNode.removeChild(div);
panes.floatPane.appendChild(div);
} else {
.
}
}
InfoBox.prototype.panMap = function () {
var map = this.map_;
var bounds = map.getBounds();
if (!bounds) return;
var position = this.latlng_;
var iwWidth = this.width_;
var iwHeight = this.height_;
var iwOffsetX = this.offsetHorizontal_;
var iwOffsetY = this.offsetVertical_;
var padX = 40;
var padY = 40;
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var boundsSpan = bounds.toSpan();
var longSpan = boundsSpan.lng();
var latSpan = boundsSpan.lat();
var degPixelX = longSpan / mapWidth;
var degPixelY = latSpan / mapHeight;
var mapWestLng = bounds.getSouthWest().lng();
var mapEastLng = bounds.getNorthEast().lng();
var mapNorthLat = bounds.getNorthEast().lat();
var mapSouthLat = bounds.getSouthWest().lat();
var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;
var shiftLng =
(iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
(iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
var shiftLat =
(iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
(iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);
var center = map.getCenter();
var centerX = center.lng() - shiftLng;
var centerY = center.lat() - shiftLat;
map.setCenter(new google.maps.LatLng(centerY, centerX));
google.maps.event.removeListener(this.boundsChangedListener_);
this.boundsChangedListener_ = null;
};
function initialize() {
var markers = [];
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(-5.646, 20.0611),
mapTypeId: google.maps.MapTypeId.ROADMAP,
sensor: 'true'
}
var map = new google.maps.Map(document.getElementById("canvas-map"), myOptions);
var data = [
{
'id':1,
'content':'Hello my name is marker, I\'m from Google',
'position': {
'lat':-33,
'lng':150
}
},
{
'id':2,
'content':'I am the content of this infobox. Wow, what a text.<br><br>The good thing is: Tags are also possible',
'position': {
'lat':-34,
'lng':150
}
},
]
for (var i = 0; i < data.length; i++) {
var current = data[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(current.position.lat, current.position.lng),
map: map,
content: current.content
});
markers.push(marker);
marker.addListener('click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
});
google.maps.event.addListener(markers[i], "click", function (e) {
map.zoomOut();
map.setCenter(this.getPosition());
var infoBox = new InfoBox({
latlng: this.getPosition(),
map: map,
content: this.content
});
});
}
}
Answer to question 1
If you want the map to zoom out when the user closes an info window, you can listen for the closeclick event on the info window object.
infoWindow.addListener('closeclick', function() {
map.setZoom(3); // Set the desired zoom level
});
I couldn't get your code to work so I created a basic example of the above functionality in action. Clicking on the marker opens an info window and zooms the map in. Closing the info window, zooms the map back out.
Answer to question 2
Check out geocodezip's comments to your question. He provides links to previous questions that could help you figure out how to have only one info window open at a time.

How to add a text box on google maps route?

I need to create a a text box between the route directions like in here :
For start i was thinking to add tooltip...but i can't place them in the middle of the route like in the picture, or set it's position to be relative.
You can create a custom overlay as described in the documentation:
https://developers.google.com/maps/documentation/javascript/customoverlays
The sample code snippet might be
function routeOverlay(point, map, content) {
this._point = point;
this._map = map;
this.div_ = null;
this._cnt = content;
this.setMap(map);
}
routeOverlay.prototype = new google.maps.OverlayView();
routeOverlay.prototype.onAdd = function () {
var div = document.createElement('div');
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px';
div.style.backgroundColor = 'white';
div.style.position = 'absolute';
div.style.padding = '4px';
div.style.zIndex = 1000;
div.innerHTML = this._cnt;
this.div_ = div;
// Add the element to the "overlayLayer" pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
}
routeOverlay.prototype.draw = function () {
var overlayProjection = this.getProjection();
var p = overlayProjection.fromLatLngToDivPixel(this._point);
this.div_.style.left = p.x + 'px';
this.div_.style.top = p.y + 'px';
}
routeOverlay.prototype.onRemove = function () {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
routeOverlay.prototype.hide = function() {
if (this.div_) {
// The visibility property must be a string enclosed in quotes.
this.div_.style.visibility = 'hidden';
}
};
routeOverlay.prototype.show = function() {
if (this.div_) {
this.div_.style.visibility = 'visible';
}
};
Later in you code you should create this overlay. For example:
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var ind = (response.routes[0].overview_path.length - response.routes[0].overview_path.length % 2) / 2;
var rover = new routeOverlay(response.routes[0].overview_path[ind], map, 'Add your HTML here');
rover.show();
} else {
window.alert('Directions request failed due to ' + status);
}
I have modified your jsfiddle: http://jsfiddle.net/h54tmmcb/14/
You should create corresponding styles and corresponding content for the overlay.
Hope this helps!

Bullet Point not moving, only the image is

I need to animate the points in a bullet list, the bullet list is a div that contains bullet points that are divs.
A bullet point div contains an image and another div which has the bullet point text, the problem is when I try and move a given bullet point div only the image is moved.
I have tried various changes to the .style.position to no avail.
I could not create an account on jsfiddle.net so the following is a working example that moves only the first bullet point:
<html>
<head>
<title>Build Bullets</title>
<body>
<script>
window.setTimeout('initBuildBullets()',100);
function initBuildBullets(){
var bulletPointsDiv = document.createElement('div');
var bName = 'BulletList';
bulletPointsDiv.style.visibility='visible';
bulletPointsDiv.style.position = 'fixed';
bulletPointsDiv.style.display = 'block';
bulletPointsDiv.style.textAlign = 'left';
bulletPointsDiv.id = bName;
document.body.appendChild(bulletPointsDiv);
var bullet_src = 'bullet_level_1.gif';
var bulletText=[];
bulletText[0]='Bullet Point 1';
bulletText[1]='Bullet Point 2';
bulletText[2]='Bullet Point 3';
var x=100;
var y=100;
var h=100;
var w=200;
var lastBot = 0;
var indent = 0;
var imgW = 25;
var hOffset = 5;
for(var i=0;i<bulletText.length;i++){
var bp_id = bName + '_Bullet_Point_' + i;
var bulletPointDiv = document.createElement('div');
bulletPointDiv.id = bp_id;
bulletPointDiv.style.overflow = 'hidden';
bulletPointDiv.style.visibility='visible';
bulletPointDiv.style.position = 'inherit';
bulletPointDiv.style.display = 'inherit';
bulletPointDiv.style.textAlign = 'left';
bulletPointDiv.style.top = (y + lastBot) + 'px';
bulletPointDiv.style.left = (x + indent) + 'px';
var bulletImage = document.createElement('img');
bulletImage.src = bullet_src;
bulletImage.id = bName + '_Bullet_Image_' + i;
var bulletFieldDiv = document.createElement('div');
bulletFieldDiv.id = bName + '_Bullet_Field_' + i;
bulletFieldDiv.style.overflow = 'hidden';
bulletFieldDiv.style.position = 'inherit';
bulletFieldDiv.style.display = 'inherit';
bulletFieldDiv.style.textAlign = 'left';
bulletFieldDiv.style.top = (y + lastBot) + 'px';
bulletFieldDiv.style.left = (x + imgW + indent) + 'px';
bulletFieldDiv.style.width = (w - (imgW + indent)) + 'px';
bulletFieldDiv.innerHTML = bulletText[i];
bulletFieldDiv.style.visibility='visible';
bulletPointDiv.appendChild(bulletImage);
bulletPointDiv.appendChild(bulletFieldDiv);
bulletPointsDiv.appendChild(bulletPointDiv);
lastBot += bulletFieldDiv.offsetHeight + hOffset;
}
window.setTimeout('moveBullets()',100);
}
function moveBullets(){
var bp_id = 'BulletList_Bullet_Point_0';
bulletPointDiv = document.getElementById(bp_id);
bulletPointDiv.style.top = '0px';
bulletPointDiv.style.left = '0px';
}
</script>
</body>
</html>
If I could ask that you copy/paste to test.
The following image is the bullet_level_1.gif
I need to set the style.position to 'relative' and then the top and left needs to account for the image (ONLY), once I do that then all objects within the div will move with the div, e.g.:
...
var bulletImage = document.createElement('img');
bulletImage.src = bullet_src;
var imgW = bulletImage.width + 8;
var bulletFieldDiv = document.createElement('div');
bulletFieldDiv.style.position = 'relative';
bulletFieldDiv.style.top = '-' + (bulletImage.height + 8) + 'px';
bulletFieldDiv.style.left = imgW + 'px';
...
That said, I'm not sure why I need the additional 8px for both the height and width??

Google Map API - multiple icons in wrong spot

I have a very strange issue that seems to have appeared only recently. I haven't done any major code changes to the project in a while and none to the function in question in a long while.
So the problem, when I add more than one icon to Google Map using API, the icons are appearig on top of each other.
The strange thing is the labels are all correctly located but those use the same coordinates as the icons.
Here is the string that is passed to the function
1344, 52.65665917, -2.49004717, '../Images/Icons/Direction/container_blueN.ico', 'Galahad', '2014 Mar 05 Wednesday, 14:00', 'Wellington Road, Horsehay, Hollybank', 'RESERVED', '0 KPH', 0
The function is
function AddClusterLocation(FID, latitude, longitude, Icon, ID, DateStamp, Location, Event, Speed, IgnitionStatus) {
if (objMap) {
var cssName = 'MarkerIgnitionOff';
switch (IgnitionStatus) {
case '1':
cssName = 'MarkerIgnitionOn';
break;
default:
cssName = 'MarkerIgnitionOff';
}
var adjustedIcon = new google.maps.MarkerImage(
Icon,
new google.maps.Size(32, 32),
new google.maps.Point(0, 0),
new google.maps.Point(16, 16)
);
var objMarker = new MarkerWithLabel({
position: new google.maps.LatLng(latitude, longitude),
draggable: false,
raiseOnDrag: false,
icon: adjustedIcon,
map: objMap,
labelContent: ' ' + ID + ' ',
labelAnchor: new google.maps.Point(-8, -8),
labelClass: cssName, // the CSS class for the label
labelStyle: { opacity: 1.0 }
});
// Add Maker to array
objMakersArray.push(objMarker);
// Wrap the event listener inside an anonymous function
// then we immediately invoke and passes the variables to
(function (ID, DateStamp, Location, Event, Speed, Icon) {
google.maps.event.addListener(objMarker, 'click', function () {
if (!objInfoWindows) {
objInfoWindows = new google.maps.InfoWindow();
}
// Create Paragraph
var para1 = document.createElement('p');
var adiv = document.createElement('div');
adiv.style.cssText = 'width: 300px; font-family: "Lucida Grande", Helvetica, Arial, sans-serif; font-size: 10pt; color: #000000;';
// var htmlstring = '<div style="width: 300px; font-family: "Lucida Grande", Helvetica, Arial, sans-serif; font-size: 6pt; color: #FF0000;">'
var htmlstring = '<table>' // style="width: 300px; font-family: "Lucida Grande", Helvetica, Arial, sans-serif; font-size: 6pt; color: #FF0000;">'
htmlstring = htmlstring + '<tr><td style="width: 100px;"><strong>ID</strong></td><td style="width: 200px;">' + ID + '</td></tr>';
htmlstring = htmlstring + '<tr><td><strong>Date/Time</strong></td><td>' + DateStamp + '</td></tr>';
htmlstring = htmlstring + '<tr><td><strong>Location</strong></td><td>' + Location + '</td></tr>';
htmlstring = htmlstring + '<tr><td><strong>Event</strong></td><td>' + Event + '</td></tr>';
htmlstring = htmlstring + '<tr><td><strong>Speed</strong></td><td>' + Speed + '</td></tr></table>'
// htmlstring = htmlstring + '</div>';
adiv.innerHTML = htmlstring;
// para1.innerHTML = htmlstring;
para1.appendChild(adiv);
// Zoom In DIV
var aDiv = document.createElement('div');
aDiv.style.width = "100px";
aDiv.style.float = 'left';
// Zoom In
var alink = document.createElement('a');
alink.innerHTML = 'Zoom In';
alink.href = '#';
alink.onclick = function () {
objMap.setCenter(objMarker.getPosition());
zoomLevel = objMap.getZoom();
if (zoomLevel != 21) {
objMap.setZoom(zoomLevel + 1);
}
return false;
};
aDiv.appendChild(alink);
// Zoom OUT DIV
var bDiv = document.createElement('div');
bDiv.style.width = '100px';
bDiv.style.float = 'left';
// Zoom In
var blink = document.createElement('a');
blink.innerHTML = 'Zoom Out';
blink.href = '#';
blink.onclick = function () {
objMap.setCenter(objMarker.getPosition());
zoomLevel = objMap.getZoom();
if (zoomLevel != 0) {
objMap.setZoom(zoomLevel - 1);
}
return false;
};
bDiv.appendChild(blink);
// Add Favourite Div
var cDiv = document.createElement('div');
cDiv.style.float = 'right';
cDiv.style.width = '150px';
// Add Favourite
var clink = document.createElement('a');
clink.innerHTML = 'Add to Favourite';
clink.href = '#';
clink.onclick = function () {
position = objMarker.getPosition();
Pane = window.parent.ASPxSplitterDefault.GetPaneByName('PaneDisplay');
if (Pane) {
Pane.SetContentUrl('../Pages/FavouritePage.aspx?latitude=' + position.lat() + '&longitude=' + position.lng(), true);
}
return false;
};
cDiv.appendChild(clink);
var para2 = document.createElement('p');
para2.appendChild(aDiv);
para2.appendChild(bDiv);
para2.appendChild(cDiv);
// Create Master Div to hold everything
var masterDiv = document.createElement('div');
// Get name of DIV that has Atlas
var objDiv = objMap.getDiv();
var divName = objDiv.id;
// Bind to mapping Div
document.getElementById(divName).appendChild(masterDiv);
// Info Div
var infoDiv = document.createElement('div');
infoDiv.style.float = 'left';
infoDiv.style.width = '350px';
infoDiv.appendChild(para1);
infoDiv.appendChild(para2);
masterDiv.appendChild(infoDiv);
// Creating the div that will contain the detail map
var detailDiv = document.createElement('div');
infoDiv.style.float = 'right';
detailDiv.style.width = '200px';
detailDiv.style.height = '200px';
masterDiv.appendChild(detailDiv)
// Setting up small map
// Creating MapOptions for the overview map
var overviewOpts = {
zoom: 14,
icon: adjustedIcon,
center: objMarker.getPosition(),
mapTypeId: google.maps.MapTypeId.HYBRID,
disableDefaultUI: true
};
var objdetailMap = new google.maps.Map(detailDiv, overviewOpts);
// Create a marker that will show in the detail map
var objdetailMarker = new google.maps.Marker({
position: objMarker.getPosition(),
map: objdetailMap,
icon: adjustedIcon,
clickable: false
});
// Setting the content of the InfoWindow
objInfoWindows.setContent(masterDiv);
// Tying the InfoWindow to the marker
objInfoWindows.open(objMap, objMarker);
});
})(ID, DateStamp, Location, Event, Speed, Icon);
objMarker = null;
}
}
The function that would call this would be
function OnCurrentPosition(arg) {
if (arg == null) {
parent.location = '../Security/Login.aspx';
}
if (arg) {
var latitude, longitude
var arrayList = arg.split(";");
alert(arg);
for (i = 0; i < arrayList.length; i++) {
if (arrayList[i].length) {
var arrLocation = arrayList[i].split("$")
AddClusterLocation(arrLocation[0], arrLocation[1], arrLocation[2], arrLocation[3], arrLocation[4], arrLocation[5], arrLocation[6], arrLocation[7], arrLocation[8], arrLocation[9]);
SetBounds(arrLocation[1], arrLocation[2]);
latitude = arrLocation[1];
longitude = arrLocation[2];
}
}
CreateClusterer();
if (flgLockMapToBounds == false) {
if (objMakersArray.length == 1) {
SetMapCentre(latitude, longitude, 14);
}
else {
ZoomToExtend();
}
}
}
}
arg = 1344$52.65665917$-2.49004717$../Images/Icons/Direction/container_blueN.ico$Galahad$2014 Mar 05 Wednesday, 14:00$Wellington Road, Horsehay, Hollybank$RESERVED$0 KPH$0$0.00000000$0.00000000$0;1342$52.65582367$-2.48958417$../Images/Icons/Direction/container_yellowN.ico$Gwinevere$2014 Mar 05 Wednesday, 14:00$Woodlands Lane, Horsehay, Coalbrookdale$RESERVED$0 KPH$0$0.00000000$0.00000000$0;
I'm really at a lost to explain this as the labels are correct, I've checked the latitude and longitude and its different each time the function is called. Plus this was working, only spotted by customer yesterday that it wasn't.
Here's the API that I use
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
Thank you for reading the question, hopefully you be able to help!
Jim
There is an issue with the MarkerWithLabel library. Issue.
MarkerWithLabel v1.1.10 stopped working for me recently after Google Maps Api's experimental version became v3.18. I had Maps API set to "...maps/api/js?v3&..." which by default picks latest experimental version (currently v3.18). By fixing the version to v3.17 MarkerWithLabel worked fine.

Where to insert revert 'invalid'

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/

Categories