I am taking marker details from a database.
The code is
app.entries[id].data = {'id': id, 'map': entry[1].innerHTML,'type_id':
entry[2].innerHTML,'name': entry[3].innerHTML,'descript': entry[4].innerHTML, 'parish':
entry[5].innerHTML,'zip': entry[6].innerHTML, 'url': entry[7].innerHTML, 'lng':
entry[8].innerHTML,'lat':entry[9].innerHTML,'tags':entry[10].innerHTML,'img':
entry[11].innerHTML,'imgs':entry[12].innerHTML};
app.entries[id].data.imgHTML = (app.entries[id].data.img == "") ? "" :
fill_template(app.entries[id].data,app.infoWindowImageHTML);
var str = fill_template(app.entries[id].data,app.searchRowHTML);
html.push(str);
if (app.entries[id].data.lat != 0 || app.entries[id].data.lng != 0) {
var point = new GLatLng(app.entries[id].data.lat,app.entries[id].data.lng);
var m = new GMarker(point,{draggable: true});
GEvent.addListener(m, "dragstart", function() {
// map.closeInfoWindow();
var latlngold = m.getLatLng();
});
GEvent.addListener(m, "dragend", function() {
var m = new GMarker(point,{draggable: true});
m.entry_id = id;
var p=m.entry_id;
var latlngnew = m.getLatLng();
alert(latlngnew);
//m.setLatLng(new GLatLng(latlng));
editentry1(latlngnew,p);
});
}
The dragend and dragstart function always takes the last marker's details not the details of dragging marker..
function editentry1(latlngnew,p){
var newlat=latlngnew.lat();
var newlng=latlngnew.lng();
var d = new Date();
var dv = d.valueOf();
var url = "<?php echo $g['appPath']; ?>admin/editPoint.php?d="+dv+"&
newlat="+newlat+"newlng="+newlng+"&p="+p;
var s = $('mapStatus');
s.innerHTML = "EDiting Point...";
s.show();
new Ajax.Request(url, {
method: 'get',
onSuccess: editEntryReturn,
onFailure: requestFailed
});
}
editPoint.php
require("createThumb.php");
$newlng = $_GET['newlng'];
$newlat = $_GET['newlat'];
$p=$_GET['p'];
$q = "UPDATE entry SET lat = '$newlat', lng = '$newlng' WHERE id='$p';";
$r = updateBatch($q);
}
?>
but the position of the marker doesn't changes
Wrap your marker creation code in a function. This will create a closure in which the drag callbacks can find the appropriate marker object:
function createMarker (point)
{
var m = new GMarker(point,{draggable: true});
GEvent.addListener(m, "dragstart", function() {
var latlngold = m.getLatLng();
});
GEvent.addListener(m, "dragend", function() {
var latlngnew = m.getLatLng();
editentry1(latlngold,latlngnew);
});
return m;
}
Call this from inside your if statement after getting the point:
if (app.entries[id].data.lat != 0 || app.entries[id].data.lng != 0)
{
var point = new GLatLng(app.entries[id].data.lat,app.entries[id].data.lng);
map.addOverlay(createMarker (point));
}
Related
I have a Flask python application where the user can select a vehicle in the web page and depending on which vehicle is selected, the application should propose different WMS layers in the Leaflet layer control that the user can tick on / off depending of his needs. The logic of feeding new layers depending of vehicle selection is done via ajax, where the layers vs vehicle is fetched from a database.
This works fine the first time the vehicle is selected, however, when a different vehicle is selected and then the first vehicle again, the WMS layer does not show in the leaflet map, though the layer name can be selected in the layer control. To avoid having too many checkboxes the vessels has been added to the same marker group so the user only have the vessel group and a couple WMS layers to tick on/off.
I'm sure the solution is dead simple. However have been exhausing 'every' tip I could find on different forums.
JavaScript:
var vesselVar = null;
var mapVessel = null;
var layerControl = null;
var baseMaps = null;
var overlayMaps = null;
var layerNameArr = null;
var layerLinkArr = null;
var baseMapArr = null;
var myVessels = null;
var sLayerName = null;
var sUrl = null;
var wmsOptions = null;
var myWmsLayer = null;
function myOnSelectedVessel() {
let sSelectedVessel = $('#sSelectedVessel').find(":selected").text()
if (sSelectedVessel.length > 0) {
$.ajax({
url: '/vessel_map_set_vessel_id',
data: {
'sSelectedVesselName': sSelectedVessel,
},
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.result) {
alert(response.msg);
}
myCreateOverlay(response.liVessels, response.liLastVesselPos, response.arrLeaflet.toString());
myCreateBaseLayers();
myCreateMap(response.lat, response.lon);
mapVessel.panTo(new L.LatLng(parseFloat(response.lat), parseFloat(response.lon)));
},
error: function (error) {
alert("error in function vessel_map.myOnSelectedVessel");
}
});
}
}
function myCreateVesselGroup(liVessels, liLastVesselPos) {
try {
myVessels = null;
vesselVar = null;
myVessels = L.layerGroup([]);
vesselVar = [];
let iLen = liLastVesselPos.length;
const arrVesselNames = liVessels.toString().split(',');
const arrVesselPos = liLastVesselPos.toString().split(',');
let iCntVesselPos = 0;
for (let iCn7 = 0; iCn7 < iLen; iCn7++) {
arrPos = liLastVesselPos[iCn7];
//alert(arrVesselNames[iCn7]);
myAddVesselMarker(arrVesselNames[iCn7], arrVesselPos[iCntVesselPos], arrVesselPos[iCntVesselPos + 1]);
myVessels.addLayer(vesselVar[iCn7]);
iCntVesselPos += 2;
}
}
catch (err) {
alert("Error in function myCreateBaseLayers: " + err.message);
}
}
function myCreateOverlay(liVessels, liLastVesselPos, sLeafletWmsString) {
try {
if (mapVessel !== null) {
if ((overlayMaps !== null) && (layerControl !== null)) {
mapVessel.eachLayer(function (layer) {
mapVessel.removeLayer(layer);
});
}
}
overlayMaps = null;
overlayMaps = {};
myCreateVesselGroup(liVessels, liLastVesselPos)
overlayMaps['Vessels'] = myVessels;
if (sLeafletWmsString.length > 1) {
const arrLeaflet2 = sLeafletWmsString.split(',')
let iLen = arrLeaflet2.length;
for (let iCnt4 = 0; iCnt4 < iLen; iCnt4 += 2) {
sLayerName = null;
sLayerName = arrLeaflet2[iCnt4].toString();
wmsOptions = null;
wmsOptions = {};
wmsOptions.layers = sLayerName;
wmsOptions.format = 'image/png';
wmsOptions.transparent = true;
wmsOptions.opacity = 0.5;
sUrl = null;
sUrl = arrLeaflet2[iCnt4 + 1];
myWmsLayer = null
myWmsLayer = new L.tileLayer.wms(sUrl, wmsOptions);
overlayMaps[sLayerName] = myWmsLayer;
}
}
}
catch (err) {
alert("Error in function myCreateOverlay: " + err.message);
}
}
function myCreateBaseLayers() {
try {
layerNameArr = null;
layerLinkArr = null;
baseMaps = null;
layerNameArr = [];
layerLinkArr = [];
baseMaps = []
layerNameArr.push('OpenStreetMap');
layerLinkArr.push(L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: 'OpenStreetMap', transparent: true }));
for (iCn2 = 0; iCn2 < layerLinkArr.length; iCn2++) {
baseMaps[layerNameArr[iCn2]] = layerLinkArr[iCn2];
}
}
catch (err) {
alert("Error in function myCreateBaseLayers: " + err.message);
}
}
function myAddVesselMarker(sTitle, dLat, dLon) {
try {
var markerOptions = {};
markerOptions.title = sTitle;
markerOptions.clickable = true;
markerOptions.draggable = false;
var sPopupText = "Lat: " + dLat.toString() + ", Lon: " + dLon.toString();
vesselVar.push(L.marker([dLat, dLon], markerOptions).bindPopup(sPopupText));
}
catch (err) {
alert("Error in function myAddVesselMarker: " + err.message);
}
}
function myCreateMap(dLatCenter, dLonCenter) {
try {
if (mapVessel !== null) {
mapVessel.invalidateSize();
mapVessel.off();
mapVessel.remove();
}
mapVessel = null;
layerControl = null;
mapVessel = new L.map('map', { center: [dLatCenter, dLonCenter], zoom: 13, layers: [layerLinkArr[0]] });
layerControl = new L.control.layers(baseMaps, overlayMaps).addTo(mapVessel);
}
catch (err) {
alert("Error in function myCreateMap: " + err.message);
}
}
For anybody else that struggles with the same issue. My problem was that the '&' character in the url string is a javascript entity character that is interpreted as javascript code (even though the url string was a varaiable and not in the JS code itself). For the first on load draw I used Flask's Jinja2, which automatically modified all the '&' characters in the url string, hence why the first time draw showed up ok. Once I replaced all the '&' characters in the ajax string, that I sent back to javascript when the user changed a vehicle, with '&', the overlay showed up also when I changed the vehicle.
I am using Mapbox to draw the polyline between the points on map, but the line is messy it is not printing as per the map routes can someone please help me with this or please suggest some alternatives.
var myMap = L.mapbox.map('map')
.setView([34.2445899, -119.1842238], 13)
.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));
var markers = new L.MarkerClusterGroup();
var refreshRealTime;
var featureLayer = L.mapbox.featureLayer().addTo(myMap);
request.onreadystatechange = function () {
if (this.readyState === 4) {
let body = JSON.parse(this.responseText);
let coords_line = [];
let stopArr = [];
for(let i=0; i<body.length; i++){
let data = body[i];
let stop = data.stop;
if(!stopArr.includes(stop.name)){
coords_line.push([stop.lat, stop.lon ]);
let marker = L.marker(new L.LatLng(stop.lat, stop.lon), {
icon: L.mapbox.marker.icon({'marker-symbol': 'bus', 'marker-color': '0044FF', 'description':'<div><p><b>Cpanacity: </b></div>'}),
title: stop.name
});
marker.bindPopup(stop.name);
markers.addLayer(marker);
stopArr.push(stop.name);
}
}
myMap.addLayer(markers);
if(coords_line.length > 0){
myMap.setView(coords_line[0], 13);
setTimeout(function(){
let routeId= $("#route").val();
let routecolor = routeObj[routeId].color;
polyline = L.polyline(coords_line, {color: routecolor}).addTo(myMap);
}, 1000);
}
}
};
After debugging I found the solution, in that first we need to call the direction API based on given points
$.get('https://api.mapbox.com/matching/v5/mapbox/driving/' + qry + '?geometries=geojson&steps=true&access_token='+token,
function( data ) {
// var coords = polyline.decode(data.routes[0].geometry);
var coords = data.matchings[0].geometry.coordinates;
let coords_line = [];
for(let i=0; i<coords.length; i++){
coords_line.push([coords[i][1],coords[i][0]]);
}
polyline = L.polyline(coords_line, {color: '<?= $color ?>'}).addTo(myMap)
then we should print the polylines
Full Code is here
var myMap = L.mapbox.map('map')
.setView([34.2445899, -119.1842238], 13)
.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));
var markers = new L.MarkerClusterGroup();
var refreshRealTime;
var featureLayer = L.mapbox.featureLayer().addTo(myMap);
request.onreadystatechange = function () {
if (this.readyState === 4) {
let body = JSON.parse(this.responseText);
let coords_line = [];
let stopArr = [];
let qry = [];
for(let i=0; i<body.length; i++){
let data = body[i];
let stop = data.stop;
if(!stopArr.includes(stop.name)){
coords_line.push([stop.lat, stop.lon ]);
qry.push(stop.lon+','+stop.lat);
let marker = L.marker(new L.LatLng(stop.lat, stop.lon), {
icon: L.mapbox.marker.icon({'marker-symbol': 'bus', 'marker-color': '0044FF', 'description':'<div><p><b>Cpanacity: </b></div>'}),
title: stop.name
});
marker.bindPopup(stop.name);
markers.addLayer(marker);
stopArr.push(stop.name);
}
}
myMap.addLayer(markers);
if(coords_line.length > 0){
myMap.setView(coords_line[0], 13);
setTimeout(function(){
let routeId= $("#route").val();
let routecolor = routeObj[routeId].color;
calculateRoute(qry.join(";"));
}, 1000);
}
}
};
function calculateRoute(qry) {
$.get('https://api.mapbox.com/matching/v5/mapbox/driving/' + qry + '?geometries=geojson&steps=true&access_token='+token,
function( data ) {
// var coords = polyline.decode(data.routes[0].geometry);
var coords = data.matchings[0].geometry.coordinates;
let coords_line = [];
for(let i=0; i<coords.length; i++){
coords_line.push([coords[i][1],coords[i][0]]);
}
polyline = L.polyline(coords_line, {color: '<?= $color ?>'}).addTo(myMap)
// addRoute(coords);
// var line = L.polyline(coords).addTo(myMap);
});
}
map view
var map = L.mapbox.map('map', undefined, options);
map.setView([56.413300, 8.869450], 16)
var markerpositions;
map.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/satellite-streets-v9'));
// L.Control.geocoder().addTo(map);
var geocoder = L.control.geocoder('search-MKZrG6M').addTo(map);
L.marker([56.41083875205333, 8.864636421203615], {icon: HydrantIcon}).addTo(map).bindPopup("Hydrant 1");
L.marker([56.41069629842804, 8.868584632873537], {icon: HydrantIcon}).addTo(map).bindPopup("Hydrant 2");
L.marker([56.40941419180167, 8.866181373596193], {icon: HydrantIcon}).addTo(map).bindPopup("Hydrant 3");
var data = <?php echo JSON_encode($geojson); ?>;
var geoJsonLayer = L.geoJson().addTo(map);
function requestGeoJson(){
fetch('https://laerkeholt.dk/admin/get-features')
.then(function(response){ return response.json() })
.then(function(json){
geoJsonLayer.clearLayers().addData(json).bindPopup('ID: + IDHERE');
var http = new XMLHttpRequest();
var url = "https://maker.ifttt.com/trigger/vandingsmaskine/with/key/";
http.open("POST", url, true);
http.send(JSON.stringify({"value1": "ID 1"}));
var hydrat1 = [56.41083875205333, 8.864636421203615];
var hydrat2 = [56.41069629842804, 8.868584632873537];
var hydrat3 = [56.40941419180167, 8.866181373596193];
var test = L.latLng(json).distanceTo(hydrat1);
<?php echo $test ?>
setTimeout(requestGeoJson, 5000);
});
};
requestGeoJson();
So basically I want to have it so geoJsonLayer binds a popup with the id it got for the response JSON so each marker would be assigned its specific id from the response JSON.
I have tried todo json.properties.id to try and get the ID
You can use either pointToLayer or onEachFeature for this.
When you instantiate the geoJSON layer, use this:
var geoJsonLayer = L.geoJson(false, {onEachFeature: addMyPopup}).addTo(map);
// Initialise the three reference points
var hydrat1 = L.latLng(<..>, <..>);
var hydrat2 = L.latLng(<..>, <..>);
var hydrat3 = L.latLng(<..>, <..>);
// This gets called for every point in the GeoJSON
function addMyPopup ( feature, layer) {
if ((layer.getLatLng().distanceTo(hydrat1) < 5)
||(layer.getLatLng().distanceTo(hydrat2) < 5)
||(layer.getLatLng().distanceTo(hydrat3) < 5)) {
// Do something
}
layer.bindPopup("My ID is: " + feature.properties.id);
i was tested to the IdentyfyTask.
But I could not get a response before the value addCallback.
i want to the pnu values.
But pnu vaule was alwayes undefined...
my code is follows.
function poiClick(){
agmap.addEvent("click", function(evt){
getPoi= krcgis.Function.PoiClick(agmap ,evt);
console.log("X === ",getPoi.x);
console.log("Y === ",getPoi.y);
console.log("PNU === ",getPoi.pnu);
});
}
PoiClick : function(map, evt) {
poiInfo = {};
poiInfo.x =evt.mapPoint.x;
poiInfo.y =evt.mapPoint.y;
var targetLayerId = 'LP_PA_CBND';
var url = map.Layers.getLayerInfo(targetLayerId).SVC_URL;
var map = map.getMap();
//파라미터 설정.
var idParams = new krcgis.core.tasks.IdentifyParameters();
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.returnGeometry = true;
idParams.tolerance = 0;
idParams.layerOption = krcgis.core.tasks.IdentifyParameters.LAYER_OPTION_ALL;
idParams.width = map.width;
idParams.height = map.height;
idTask = new krcgis.core.tasks.IdentyfyTask(url);
idTask
.execute(idParams)
.addCallback(function (response) {
if (response) {
poiInfo.pnu =response[0].value;
}
});
return poiInfo;
}
The results were as follows.
IdentifyTask returns a IdentifyResult object. so you code response[0].value will be undefined.
you should use something like response[0].feature.attributes.PNU
jQuery(document).ready(function($) {
var currentMap;var lat;var log;var latlongarray;var latitude;
var longitude;var count = 0;var name;var number;var country;
var maps;var address;var marker;var batch = [];
showTooltip = function(marker) {
tooltip.innerHTML = marker.tooltip;
var point = currentMap.getCurrentMapType().getProjection()
.fromLatLngToPixel(currentMap.fromDivPixelToLatLng(
new GPoint(0, 0),true),currentMap.getZoom());
var offset = currentMap.getCurrentMapType().getProjection()
.fromLatLngToPixel(marker.getPoint(),
currentMap.getZoom());
var anchor = marker.getIcon().iconAnchor;
var width = marker.getIcon().iconSize.width;
var height = tooltip.clientHeight;
var pos = new GControlPosition(G_ANCHOR_TOP_LEFT,
new GSize(offset.x - point.x - anchor.x + width,
offset.y - point.y - anchor.y - width));
pos.apply(tooltip);
tooltip.style.visibility = "visible";
}
initialize = function() {var tim = (new Date).getTime();
var provNum = $("input[name='providerNumber']").val();
$.getJSON('newmap.do?t=' + tim+ '&providerNumber='+ provNum,
function(data) {$.each(data,function(i,item) {
address = item.name + item.address;
name = item.name;
latitude = item.lattitude;
longitude = item.longitude;
number = item.number;
var icon = new GIcon();
icon.image = "images/pin.png";
icon.iconAnchor = new GPoint(16,16);
icon.infoWindowAnchor = new GPoint(16,0);
icon.iconSize = new GSize(32,32);
icon.shadowSize = new GSize(59,32);
marker = new GMarker(new GLatLng(item.lattitude,
item.longitude),{
draggable : true,
icon : icon
});
lat = item.lattitude;
log = item.longitude;
marker.disableDragging();
batch.push(marker);
marker.tooltip = "<div class='tooltip'>"+item.name+
'<br>'+ item.number+'<br>BEDS:'+ item.bed
+ '<br>DSH: '+ item.dsh+ "</div>";
GEvent.addListener(marker,"mouseover",function() {
showTooltip(marker);
});
GEvent.addListener(marker,"mouseout",function() {
tooltip.style.visibility = "hidden";
});
GEvent.addListener(marker,"mouseout",function() {
tooltip.style.visibility = "hidden";
});
});
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map-c"));
map.setCenter(new GLatLng(lat,log),11);
tooltip = document.createElement("div");
map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
tooltip.style.visibility = "hidden";
map.setUIToDefault();
mgr = new MarkerManager(map);
mgr.addMarkers(batch,2);
mgr.refresh();
currentMap = map;
}
});
});
}
if (jQuery.browser.safari&& document.readyState != "complete") {
initialize();
}
});
This is my code.. here iam getting lattitude and longitude from sql and adding marker in google map.Now iam trying to add infobox for each marker
but i got an error
" Uncaught TypeError: pos.apply is not a function "
at line
"pos.apply(tooltip);"
Do anyone know how to solve this?
.apply is part of Function.prototype, it is not available in normal object.
let me show you, what you are doing here.
var obj = {i : 10}
obj.apply(this); //Uncaught TypeError: obj.apply is not a function
You are Creating an object from new GControlPosition and on this object .apply is not available