Good Day to everyone, Im developing a site that has a mapping features.
My goal here is make it drag if you click the marker.
Here is my code
else if (select1.value === "Arson"){
var note = document.getElementById('note');
var datepick = document.getElementById('demo1');
var timepick = document.getElementById('timepick');
layerpoly.on('click', function(e){
var markerA = new L.Marker(e.latlng,{icon: Icon1});
markerA.bindPopup("</a><br><strong>ARSON</strong></br><strong>Date:</strong>"+datepick.value+"</br><strong>Time:</strong>"+timepick.value+"</br><strong>Address:</strong>"+note.value+"<strong><br><strong>Suspect Sketch</strong><br><a href=legends/suspect.jpg rel=lightbox><img src = legends/suspect.jpg height=100 width = 100/><br> ").addTo(map);
closure1 (markerA)
var ll = markerA.getLatLng();
document.querySelector('#userLat').value = ll.lat;
document.querySelector('#userLng').value = ll.lng;
marker.dragging.enable();
});
}
The output of the code above is if i select arson. I will place a marker on map.
My question is how can i make it draggable if click that marker?
by the way this code
document.querySelector('#userLat').value = ll.lat;
document.querySelector('#userLng').value = ll.lng;
is connected into two textboxes with id of userLat and useLng. How can i update this textbox if i drag that marker?
Any Help? TY
Here's the documentation for L.Marker: http://leafletjs.com/reference.html#marker As you can see there is absolutely no method called dragging.enable so calling marker.dragging.enable(); will never work and should throw an obvious error to your browserconsole. There is however a draggable option which you can use when you instanciate the marker:
var markerA = new L.Marker(e.latlng,{
icon: Icon1,
draggable: true
});
Here's a working example on Plunker: http://plnkr.co/edit/Au3XlD?p=preview
Related
I'm trying to implement a 'filter' feature into my leaflet map alongside marker clusterer, I have got as far as having the control box and plotting the markers however upon unticking a 'category' nothing updates on the map I have attatched an example of which this feature is working http://jsfiddle.net/RogerHN/31v2afte/2/
this is how I plot the marker.
case 'antisocialbehaviour':
marker = L.marker(new L.LatLng(a[0], a[1]), {
icon: icons,
title: 'antisocialbehaviour'
});
markers_cluster.addLayer(marker);
break;
required code for control box ( top of javascript )
var groupA = L.layerGroup(markersA);
var groupB = L.layerGroup(markersB);
var markersA = [];
var markersB = [];
var overlayMaps = {
"A": groupA,
"B": groupB
};
L.control.layers(tileLayer, overlayMaps, {position:'topleft'}).addTo(map);
My code on JSFiddle if anybody needs to see the problem.
https://jsfiddle.net/jgov83fg/25/
I made a copy of your JSFiddle and made some changes to it.
I included the Leaflet.MarkerCluster.LayerSupport sub plugin in the body tag of the JSFiddle's HTML:
<script src="https://unpkg.com/leaflet.markercluster.layersupport#2.0.1/dist/leaflet.markercluster.layersupport.js"></script>
I added the following to the JavaScript code:
var mcgLayerSupportGroup = L.markerClusterGroup.layerSupport(),
group1 = L.layerGroup(),
group2 = L.layerGroup(),
group3 = L.layerGroup(),
group4 = L.layerGroup(),
control = L.control.layers(null, null, {
collapsed: false
}),
i, a, title, marker;
mcgLayerSupportGroup.addTo(mymap);
mcgLayerSupportGroup.checkIn([group1, group2, group3, group4]);
control.addOverlay(group1, 'Anti-Social Behaviour');
control.addOverlay(group2, 'Violent Crime');
control.addOverlay(group3, 'Bicycle Theft');
control.addOverlay(group4, 'Burglary');
control.addTo(mymap);
group1.addTo(mymap); // Adding to map or to AutoMCG are now equivalent.
group2.addTo(mymap);
group3.addTo(mymap);
group4.addTo(mymap);
Then, in the create_marker function, I call either marker.addTo(group1), marker2.addTo(group2), marker3.addTo(group3) or marker4.addTo(group4) based on the type of the crime the marker is associated with.
Hope this helps, let me know if you have any questions.
I am working with leaflet and wanted to add some custom controls on my leaflet map. That worked fine. However my problem is, that those custom controls are more in front of the map and not 'on' the map.
So here an example to better understand what i mean: (the navbar is in the same html file as the leaflet map)
I have a navbar and beneath there is the leaflet map. In the left corner of the leaflet map is a custom control (compass). So now when I use the dropdown menu from the navbar, i barely can click on on of the options, as the custom control is 'in front of it' and is blocking the hit bock. (picture below).
Is there a way to put the custom control more on the map than in front of the map?
Here is my custom control (compass):
onAdd: function() {
var controlDiv = L.DomUtil.create('div', 'leaflet-compass');
L.DomEvent
.addListener(controlDiv, 'click', L.DomEvent.stopPropagation)
.addListener(controlDiv, 'click', L.DomEvent.preventDefault);
var compassDiv = document.createElement('div');
compassDiv.id = 'compassGroup';
var compassImage = document.createElement('img');
compassImage.id = 'cpImage';
compassImage.setAttribute('src', 'images/kompass.png');
var speedHeadline = document.createElement('h2');
speedHeadline.id = 'speedHL';
var arrowImage = document.createElement('img');
arrowImage.id = 'arImage';
arrowImage.setAttribute('src', 'images/arrow.png');
controlDiv.appendChild(compassDiv);
compassDiv.appendChild(compassImage);
compassDiv.appendChild(arrowImage);
controlDiv.appendChild(speedHeadline);
return controlDiv;
}
});
L.control.compass = function(options) {
return new L.Control.Compass(options);
};
function initCompass(map, timestamp) {
var compassControl = L.control.compass();
map.addControl(compassControl);
rotateCompass(timestamp);
}
I m using draggable markers + 2 autocompletes to get directions.
https://developers.google.com/maps/documentation/javascript/examples/directions-draggable.
I have a listener who catch events when marker has a new position.
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
var place1 = autocompleteFrom.getPlace();
var coord1 = [place1.geometry.location.lat(), place1.geometry.location.lng()];
var place2 = autocompleteTo.getPlace();
var coord2 = [place2.geometry.location.lat(), place1.geometry.location.lng()];
});
The problem is autocompleteFrom.getPlace() returns undefined when user has not enter a place in the autocomplete search box.
Is it possible to setup a default location for the autocompletes ?
I am sorry because I don't have enough reputation to comment.
You could set default location for place1, this is more simple than set default for autocompleteform.
I am using the Geolocation Marker Script from the Google Maps Utilities Library V3 in order to display the position of a user.
What I want to achieve (I am a newbie to the Google Maps API!) is:
have the users current coordinates displayed (e.g. in a simple CSS container somewhere on the page)
connect an event to a marker. I should be triggered when the user is close.
Appreciate your help!
To display coordinates to the user, you would need a reference to a DOM Element. Then it's a simple matter of updating the content.
HTML On the Page
<div id="UserCoordinates">Waiting on GPS Position ...</div>
In Script
google.maps.event.addListener(GeoMarker, 'position_changed', function() {
var UserPosition = this.getPosition();
var DisplayElement = document.getElementById('UserCoordinates');
if(UserPosition === null) {
DisplayElement.innerHTML = 'Waiting on GPS Position...';
} else {
DisplayElement.innerHTML =
'Current Position: ' + UserPosition.toUrlValue();
}
});
This will show the user their current position as it changes. If you are going to continue using a full screen map, you'll probably want to implement the UserCoordinates div as a map control. The API Reference has a good overview and multiple examples on this.
Display an info window when the user is within X meters of a location
This is a little tricky because there are multiple scenarios to handle and you don't want the infowindow opening repeatedly as they move within your radius.
Distance calculation
I see you have a distance function in your code, but I recommend using the one in the Spherical Geometry library of the API. You just have to specifically load the library with your api script tag:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true_or_false">
</script>
Then you need to add to the position_changed event handler:
var IsWithinRadius = false; //assume they start outside of the circle
var RadiusInMeters = 1000; //within 1 km
var LocationOfInterest = map.getCenter();
google.maps.event.addListener(GeoMarker, 'position_changed', function() {
var UserPosition = this.getPosition();
var DisplayElement = document.getElementById('UserCoordinates');
if(UserPosition === null) {
DisplayElement.innerHTML = 'Waiting on GPS Position...';
IsWithinRadius = false; //you don't know where they are
} else {
DisplayElement.innerHTML =
'Current Position: ' + UserPosition.toUrlValue();
var IsCurrentPositionInRadius =
Math.abs(google.maps.geometry.spherical.computeDistanceBetween(
UserPosition, LocationOfInterest)) <= RadiusInMeters;
var JustEnteredRadius = !IsWithinRadius && IsCurrentPositionInRadius;
IsWithinRadius = IsCurrentPositionInRadius;
if(JustEnteredRadius) {
//trigger action here.
alert("Within raidus");
}
}
});
I'm trying to add custom controls to a Google map using the API. I already have two custom controls added and they work just fine. I tried to copy and paste the code for a third control (changing the relevant variables of course) and I keep getting the above error (in the title).
Chrome console and Firebug don't seem to point to a particular problem (it breaks inside the google maps api code). By progressively commented out lines, I've narrowed it down to this particular line:
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(churchControlDiv);
The full code for adding the control is as follows:
function ChurchControl(churchControlDiv, map) {
churchControlDiv.style.padding = '5px 0px';
var churchControlUI = document.createElement('DIV');
churchControlUI.style.backgroundColor = 'white';
churchControlUI.style.borderStyle = 'solid';
churchControlUI.style.borderWidth = '1px';
churchControlUI.style.borderColor = 'gray';
churchControlUI.style.boxShadow = 'rgba(0, 0, 0, 0.398438) 0px 2px 4px';
churchControlUI.style.cursor = 'pointer';
churchControlUI.style.textAlign = 'center';
churchControlUI.title = 'Click to see Churches';
churchControlDiv.appendChild(churchControlUI);
var churchControlText = document.createElement('DIV');
churchControlText.style.fontFamily = 'Arial,sans-serif';
churchControlText.style.fontSize = '13px';
churchControlText.style.padding = '1px 6px';
churchControlText.style.fontWeight = 'bold';
churchControlText.innerHTML = 'Churches<br>แสดงจำนวนคริสเตียน';
churchControlUI.appendChild(churchControlText);
google.maps.event.addDomListener(churchControlUI, 'click', function() {
toggle(churches);
if (churchControlText.style.fontWeight == 'bold') {
churchControlText.style.fontWeight = 'normal';
} else {
churchControlText.style.fontWeight = 'bold';
}
});
google.maps.event.addDomListener(churchControlUI, 'mouseover', function() {
churchControlUI.style.backgroundColor = '#e8e8e8';
});
google.maps.event.addDomListener(churchControlUI, 'mouseout', function() {
churchControlUI.style.backgroundColor = 'white';
});
}
function initialize(){
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: centerLatLng,
zoom: 7,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var churchControlDiv = document.createElement('DIV');
var churchControlDiv = new ChurchControl(churchControlDiv, map);
churchControlDiv.index = 3;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(churchControlDiv);
}
Any ideas? Any reason why having 3 controls would be a problem?
I had the same error pop up on my console whilst following the tutorial for a different reason.
Rather than using default javascript DOM manipulation, I'd been using jQuery to create my elements, e.g.
var controlDiv = $('<div></div>');
var controlUI = $('<div class="alert alert-info"></div>');
controlDiv.append(controlUI);
var controlText = $('<div>Control text here</div>');
controlUI.append(controlText);
Doing this is fine, so long as you give the DOM node to the map (and not the jQuery element!) at the end, using controlUI[0] or controlUI.get(0), like this:
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv[0]);
See also:
How to get the native DOM element from a jQuery object - jQuery FAQ
I followed the tutorial, which is very close to your code.
This line near the end needs to change
var churchControlDiv = new ChurchControl(churchControlDiv, map);
Replace churchControlDiv with churchControl or another name because churchControlDiv should not be overwritten.
See here http://jsfiddle.net/FTjnE/2/
I marked my changes with //CHANGED an alert for the click, and new map center
The general underlying cause of this issue seems to be the element or its properties being removed or otherwise made not present. Maps API is trying to find the zIndex in the style property.
I had this issue in a Vue app custom component that interacted with the Maps API controls. We resolved it by exercising more caution in the teardown of the component.
Basically you need to ensure that you don't add a null element to the control, and don't make the element or its properties null before removing it, by doing something funky with say, v-if.