update maker location on Mapbox js using mysql and ajax - javascript

After hours of searching I have finally got markers on my map from MySQL. the last part im struggling with is how to move the makers once the data is changed in MySQL.
currently I have.
function loadMarkers() {
$.get('ajax-get-markers.php', function (data, textStatus, jqXHR) {
var data = JSON.parse(data);
console.log(data)
Array.prototype.forEach.call(data, function(d){
console.log(d.lng, d.lat);
// make a marker for each feature and add to the map
var marker = new mapboxgl.Marker()
.setLngLat({lng: d.lng ,lat: d.lat})
.setPopup(new mapboxgl.Popup()
.setHTML("<h3>" + d.name+ "</h3>"))
.addTo(map);
});
console.log(currentMarkers)
})
}
setInterval(loadMarkers, 5000)
</script>
I have realized this just drops a marker on top of itself each call.
one option I have is to remove all the markers and re-add them but is there another way?

You would have to keep track of the markers that exist. For example you could create an array that holds the marker objects.
marker[i] = new mapboxgl.Marker()
.setLngLat({lng: d.lng ,lat: d.lat})
.setPopup(new mapboxgl.Popup()
.setHTML("<h3>" + d.name+ "</h3>"))
.addTo(map);
You can also change the markers location after they were added to the map by using
marker[i].setLngLat({lng: d.lng ,lat: d.lat})

Related

Leaflet Update Single Marker

I have a Leaflet OpenStreetMap map where I set a new marker. I want the marker to move, which would mean clearing all previous markers, and adding a new one. Currently new clicks just result in new markers, with more than one staying on the map.
How can I clear all markers upon clicking again?
initmap();
var home = new L.LayerGroup();
map.on('click', function(e) {
// clear all markers here somehow
document.getElementById("latFld").value = e.latlng.lat;
document.getElementById("lngFld").value = e.latlng.lng;
L.marker([e.latlng.lat,e.latlng.lng]).addTo(map);
});
Edit:
My original markers did not belong to a group.
L.marker([43.653409, -79.384112]).bindPopup('Original Home').addTo(map);
Regardless of the LayerGroup into a variable, I was asking if there was a way to clear all markers regardless. It is not a duplicate.
Shoved my markers into a layerGroup so I can use that for clearing:
var mymarkers = L.layerGroup([
L.marker([43.677681,-79.389943]).bindPopup('Some place'),
L.marker([<%= #mylat %>,<%= #mylon %>]).bindPopup('Original Home')
]);
L.control.layers(mymarkers).addTo(mymap);
mymap.on('click', function(e) {
mymarkers.clearLayers();
document.getElementById("latFld").value = e.latlng.lat;
document.getElementById("lngFld").value = e.latlng.lng;
L.marker([e.latlng.lat,e.latlng.lng]).bindPopup('New ome').addTo(mymarkers);
$('#update').html("Values updated");
});
I was expecting an object that automatically held all markers, but it wasn't there. So I had to assign then to one.

How to create and bind a context menu with array of markers on the Google map?

I am working on a treasure hunting project using JSP, Postgres and Tomcat. After logging in, it should allow the admin to specify the map location, add various objects (like treasure and NPCs that are already saved in my database) to the map and be able to copy, paste and delete any objects.
Everything like login, and insert objects of various types, is working but now I want to enable a right-click context menu for each marker that will give the admin 3-4 options; copy, paste, delete, edit.
To achieve this, I have found the link very useful where the source code for the context menu is provided: http://code.martinpearman.co.uk/googlemapsapi/contextmenu/1.0/src/ContextMenu.js
I created a ContextMenu.js file and copied the above code and then have the following function in my jsp file. Please note that I'm retrieving a list of markers from my database as JSON object and looping through it to create and place the markers on the map.
function drawMap(){
var markers = {};
var contextMenu;
var contextMenuOptions={};
contextMenuOptions.classNames={menu:'context_menu',
menuSeparator:'context_menu_separator'};
// create an array of ContextMenuItem objects
var menuItems=[];
menuItems.push({id: "copy", className:'context_menu_item',
eventName:'copy_click', label:'Copy'});
menuItems.push({id: "paste", className:'context_menu_item',
eventName:'paste_click', label:'Paste'});
menuItems.push({id: "delete", className:'context_menu_item',
eventName:'delete_click', label:'Delete'});
contextMenuOptions.menuItems=menuItems;
lat='43.56873147104461';
lng='-79.76628009520937';
map = new google.maps.Map(
document.getElementById("map_container"), {
center: new google.maps.LatLng(lat,lng),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
json ='<%=request.getSession().getAttribute("data")%>'
json = JSON.parse(json);
for (i = 0; i <= json.length; i++) {
var lt,ln;
lat = json[i].latstr;
lng = json[i].lngstr;
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
contextMenu = new ContextMenu(map, contextMenuOptions); //stops at this point
google.maps.event.addListener(marker, 'rightclick',function(e) {
contextMenu.show(e.latLng);
});
} //end for loop
google.maps.event.addListener(contextMenu, 'menu_item_selected',
function(object, latLng, eventName){
// latLng is the position of the ContextMenu
// eventName is the eventName defined for the clicked
ContextMenuItem in the ContextMenuOptions
switch(eventName){
case 'copy_click':
copyObject(object);
break;
case 'paste_click':
pasteObject(object, latLng);
break;
case 'delete_click':
deleteObject(object);
break;
}
});
} //end function drawMap();
I am not sure where the problem is. When I run the program, it just displays the first marker on the map and the right-click does nothing and I have tried alert("hi"); to check the problem. It stops at
contextMenu = new ContextMenu(map, contextMenuOptions);
I also tried to put an alert inside the ContextMenu function and it stops at the second line
this.setMap(map);
when I comment it out, it goes beyond this point, displays all the markers in the loop but the right-click does nothing. which means that the contextMenu.show(e.latLng); is not working. It may have something to do with the for loop.

Rendering multiple Google Maps API V3 markers from JSON

Attempting to plot multiple markers using Google Maps API V3 from JSON output by PHP from DB.
Map is initialized on page, however it does not populate with markers. Browser warns "Resource interpreted as Other but transferred with MIME type undefined."?
Suggestions for further troubleshooting / debugging please.
<!-- load points from database into Locations JSON -->
$(document).ready(function () {
$.getJSON("map-service.php?action=listpoints", function(json) {
if (json.Locations.length > 0) {
for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];
addMarker(location);
}
}
});
function addMarker(location) {
var point = new google.maps.LatLng(location.lat, location.lng);
var marker = new google.maps.Marker({
position:point,
map: map,
title: location.name
});
};
});
Validated sample JSON output from map-service.php?action=listpoints
{"Locations":[{"name":"Abco Mountain","lat":"49.424999","lng":"-125.855003"},{"name":"Adder Peak","lat":"49.248333","lng":"-125.320000"},{"name":"Alexandra Peak","lat":"49.738110","lng":"-125.489998"},{"name":"Argus Mountain","lat":"49.538612","lng":"-125.389999"},{"name":"Big Baldy Mountain","lat":"49.759998","lng":"-126.129997"}]}
My problem stemmed from how I had initialized the original map object. It wasn't visible in the code I shared ... apologies.
I did this:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
and should have done this:
this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
I found the solution in this post Adding markers after map created Thanks #yitwail !
Try using jquery $.each for your looping.
if (json && json.Locations) {
$.each(json.Locations, function() {
addMarker(this);
});
});
Also, you'll probably want to call parseFloat on the lat and longiture inside your addMarker function.

With OpenLayers, what is the correct way of removing a markers layer, and the popups?

LoadPin is a function to add a marker to a map. It initializes the layer on the first call. map is an openlayers map object.
But using map.removeLayer("markers") or "Markers", does not remove the markers from the map. I saw a mention of a destroy operation to do this but cant find that.
AND, how do I remove the popups?
var markers = null
function LoadPin(LL, name, description) {
var size = new OpenLayers.Size(36, 47);
var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
var icon = new OpenLayers.Icon('http://www.waze.co.il/images/home.png', size, offset);
if (markers == null) {
markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
}
var marker = new OpenLayers.Marker(LL, icon)
markers.addMarker(marker);
var bounds = markers.getDataExtent();
map.zoomToExtent(bounds);
map.addPopup(new OpenLayers.Popup.FramedCloud("test", LL, null,
"<div style='font-family:Arial,sans-serif;font-size:0.8em;'>" + name + "<br>" + description + "</div>",
anchor = null, true, null));
}
You can remove individual markers from a marker layer with:
markers.removeMarker(marker);
Removing the entire layer, with markers should be achieved with:
markers.destroy();
You should be able to remove a popup with:
map.removePopup(popup);
where popup is the Popup object created earlier.
I know this post is old but to remove all markers from the marker layer list use:
markerLayer.clearMarkers();
Try the any of below code i hope it will help you.
this.markerSource.removeFeature(this.iconFeature);
or
this.markerSource.removeFeature(iconFeature);

Adding pin to location clicked

I've got the following Google map on my website..
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(53.347247,-6.259031), 13);
map.setUIToDefault();
GEvent.addListener(map, "click", function(overlay, latLng)
{
// display the lat/lng in your form's lat/lng fields
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
});
}
}
What would I need to add / edit so that whenever a user clicked a location on the map a pin / balloon / any kind of indicator would be dropped at the location they clicked?
Thanks.
All you have to do is add this to your existing addListener call:
if (latLng) {
marker = new GMarker(latLng, {draggable:true});
map.addOverlay(marker);
}
See this article linked by Google in their API information for an even more advanced example that lets your users edit the map data.
Update: Changed case of 'l' to 'L' in latLng.

Categories

Resources