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);
Related
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
While re-writing one of my applications from scratch (to go from legacy to AMD) I'm encountering an error which I can't figure out. It is driving me crazy. I'm probably just misspelling something or have another minor mistake, but I just can't figure out what. Any help would be highly appreciated!
I'm still in development mode, so my code isn't that pretty at this time. You can see it live in action at here: http://tpgrf.nl/testserver/alpha/topotrainer/flevoland
The javascript code:
//Define area and url's
var currentPath = window.location.pathname.split('/');
var AREA = currentPath[currentPath.length - 2];
if (AREA == 'europa' || AREA == 'wereld' || AREA == 'nederland') {
var AREAURL = AREA;
var AREAisProvince = false;
} else {
AREAURL = 'nederland';
var AREAisProvince = true;
}; //Ondervang provincies
var basemapURL = window.location.protocol + "//tiles.arcgis.com/tiles/nSZVuSZjHpEZZbRo/arcgis/rest/services/Topografie_in_de_klas_" + AREAURL + "_ondergrond/MapServer";
var contentFeatureURL = window.location.protocol + "//services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_" + AREAURL + "/FeatureServer/0";
var CONTENT = 'cito100'; //Default to 'cito100', user can adjust manually
var TYPES = ''; //empty for now, will be defined later by the user
var TYPES = 'plaats'; //for testingunction's//
//
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
};
//
//Figure something out here to detect if the user as a new or returning visitor
//
//////////////////////////////////////
//Create a basemap and load features//
//////////////////////////////////////
var dojoConfig = { parseOnLoad: true };
var map;
require(["esri/geometry/Extent", "esri/SpatialReference", "esri/map", "esri/graphic", "esri/layers/ArcGISTiledMapServiceLayer", "esri/tasks/query", "esri/tasks/QueryTask", "esri/tasks/FeatureSet", "esri/layers/GraphicsLayer", "esri/Color", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleLineSymbol", "esri/symbols/PictureMarkerSymbol", "esri/renderers/UniqueValueRenderer", "esri/renderers/ClassBreaksRenderer",
"dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/TitlePane",
"dojo/domReady!", "dojo/dom", "dojo/on"],
function (Extent, SpatialReference, Map, Graphic, Tiled, Query, QueryTask, FeatureSet, GraphicsLayer, Color, SimpleMarkerSymbol, SimpleLineSymbol, PictureMarkerSymbol, UniqueValueRenderer, ClassBreaksRenderer, dom, on) {
//#TODO: Can we actually define this on the basemap mapserver?
if (AREA == 'nederland' || AREAisProvince == true) {
var initExtent = new Extent(-165715, 6453119, 1435181, 7205260, new SpatialReference({ wkid: 102100 }));
}
if (AREA == 'europa') {
var initExtent = new Extent(-2827847, 2851709, 6838658, 11375669, new SpatialReference({ wkid: 102100 }));
}
if (AREA == 'wereld') {
var initExtent = new Extent(-19705424, -14849545, 21700207, 21624981, new SpatialReference({ wkid: 102100 }));
}
map = new Map("map", {
extent: initExtent
});
//let's add a basemap
var tiled = new Tiled(basemapURL);
map.addLayer(tiled);
where = 'Cito100_onderdeel=1';
if (AREAisProvince == true) {
where += ' AND Provincie=\'' + AREA + '\'';
}
map.on("load", getFeaturesToMapAndStorage(where));
function getFeaturesToMapAndStorage(whereClause) {
console.log(whereClause);
//query the featureService
var query = new Query();
query.returnGeometry = true;
query.outFields = ["*"];
query.outSpatialReference = new SpatialReference({ wkid: 102100 });
query.where = whereClause;
var queryTask = new QueryTask(contentFeatureURL);
queryTask.on("complete", function (event) {
//map.graphics.clear();
var featureGraphicsLayer = new GraphicsLayer();
//#TODO: Can't we find a way to use the symbols from the featurservice directly, instead of the url's?
defaultSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([255, 0, 0]), 1),
new Color([0, 255, 0, 0.25]));
var renderer = new UniqueValueRenderer(defaultSymbol, "Type");
renderer.addValue("Plaats", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/89e5f81878a69f9cc0525c841f98af54", 11, 11));
renderer.addValue("Gebied", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/165c76bd4465728a34f6d18df4a1ec03", 28, 28));
renderer.addValue("Water", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/f9c146a401f48c4f38202e83c2e4582a", 22, 22));
renderer.addValue("Provincie", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_nederland/FeatureServer/0/images/7a5373d8f1dcd1ecc03cefbab687b97c", 38, 32));
renderer.addValue("Land", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_europa/FeatureServer/0/images/7a5373d8f1dcd1ecc03cefbab687b97c", 38, 32));
renderer.addValue("Werelddeel", new PictureMarkerSymbol("https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/Topografie_in_de_klas_wereld/FeatureServer/0/images/48f2256a49253388488d813d721c054b", 32, 38));
var features = event.featureSet.features;
var featureCount = features.length;
for (var i = 0; i < featureCount; i++) {
var graphic = features[i];
featureGraphicsLayer.add(graphic);
}
featureGraphicsLayer.renderer = renderer;
map.addLayer(featureGraphicsLayer);
//#TODO: Update localstorage
}); //end on queryTask complete
queryTask.execute(query, queryComplete);
function queryComplete() {
console.log("fire function queryComplete");
//#TODO: reset progressbar
}; //End function queryComplete
} //end function getFeaturesToMapAndStorage
//The two closing tags below are essential and close the complete DOJO part.
} //end function after require (AMD style)
); //end require
Your issue is with: map.on("load", getFeaturesToMapAndStorage(where));
You're calling getFeaturesToMapAndStorage which returns undefined, and passing that in as the "load" handler. I'm guessing that the minified version of whatever it is that you're using uses g as a reference to your handler.
Since g is undefined, you're basically saying undefined(loadEvent).
EDIT: I'm guessing you meant to do something like this:
map.on("load", function(){
getFeaturesToMapAndStorage(where);
});
EDIT 2: For clarity, I'll explain what was wrong in more detail.
The difference between what you had and what I suggested above, is that you were calling getFeaturesToMapAndStorage on the line containing map.on("load", getFeaturesToMapAndStorage(where)); (as opposed to calling it after map's load event). In order to call your function getFeaturesToMapAndStorage with a predetermined parameter, you need to call it from a function (like the anonymous function above - function(){...}) that would then be passed in as the event handler.
Alternatively, due to how you have things scoped, you could reference your where inside of getFeaturesToMapAndStorage in place of having a whereClause parameter.
Please find polygon code as below. It works only with hard-coded data and not with data passed through database.
I want to change this so data is passed through database, not hardcoded.
Polygon comes from database in following format:
var data = "POLYGON ((174.605111568859 -37.119413675388707, 174.6051123299834 -37.119449718193458, 174.60515905129122 -37.119530204987136, 174.60540067619004 -37.119779304335452, 174.60554255499551 -37.120101860545844, 174.60568043759687 -37.120235191897571, 174.60572696965184 -37.1203066677341, 174.60572849253467 -37.120378753310746, 174.60570674933629 -37.120415100973361, 174.60560757225889 -37.120515590528086, 174.60554177129595 -37.120597601350227, 174.60549026791193 -37.120823630882519, 174.6054873903158 -37.121220253972716, 174.605111568859 -37.119413675388707))"
I'm calling following function to load ESRI maps:
function LoadEsriTrees() {
var $mover = $('#thingtypecontent');
$mover.find('div#mapDiv').empty();
//it gives polygon data as prescribed in above format
var polygonData = $mover.find('input#hdndata').val();
//following code formats polygon data in required format
var check1 = (polygonData.indexOf("POLYGON ((") !== -1);
if (check1 == true)
polygonData = polygonData.replace('POLYGON ((', '[[');
var check2 = (polygonData.indexOf("))") !== -1);
if (check2 == true)
polygonData = polygonData.replace('))', ']]');
polygonData = polygonData.replace(/,\s+/g, '],[');
//create polygon data
var coords = new Array();
var allLocs = new Array();
var anchorLat = null;
var anchorLon = null;
coords = polygonData.split(" ");
var thisLocs = new Array();
var anchorCoord = null;
if ((coords.length / 2) % 2) {
anchorCoord = coords.length / 2 - 1;
}
else {
anchorCoord = coords.length / 2;
}
for (k = 0; k <= coords.length - 1; k = k + 2) {
var thisLoc = [coords[k], coords[k + 1]];
thisLocs.push(thisLoc);
allLocs.push(thisLoc);
if (k == anchorCoord) {
anchorLat = coords[k + 1];
anchorLon = coords[k];
}
}
//thisLocs finally presents data in following format:
thisLocs = [[174.605111568859, -37.119413675388707],[ 174.6051123299834, -37.119449718193458],[ 174.60515905129122, -37.119530204987136],[ 174.60540067619004, -37.119779304335452],[ 174.60554255499551, -37.120101860545844],[ 174.60568043759687 , -37.120235191897571],[ 174.60572696965184 , -37.1203066677341],[ 174.60572849253467, -37.120378753310746],[ 174.60570674933629 , -37.120415100973361],[ 174.60560757225889, -37.120515590528086],[ 174.60554177129595, -37.120597601350227],[ 174.60549026791193, -37.120823630882519],[ 174.6054873903158, -37.121220253972716],[ 174.605111568859, -37.119413675388707]]
var map;
require([
"esri/map",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/SimpleLineSymbol",
"dojo/_base/Color",
"esri/graphic",
"esri/geometry/Polygon",
"dojo/on",
"dojo/dom",
"dojo/domReady!"
],
function (
Map, SimpleFillSymbol, SimpleLineSymbol, Color,
Graphic, Polygon,
on, dom
) {
map = new Map("mapDiv", {
center: [174.605369, -37.120276],
zoom: 15,
basemap: "streets"
});
on(map, "load", addGraphic);
var sfs = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25])
)
function addGraphic() {
// Draw polygon
var singleRingPolygon = new esri.geometry.Polygon(); singleRingPolygon.addRing(thisLocs);
singleRingPolygon.spatialReference = new esri.SpatialReference({ wkid: 4326 });
var poly_wm = esri.geometry.geographicToWebMercator(singleRingPolygon);
var gra = new Graphic(poly_wm, sfs);
map.graphics.add(gra);
}
});
}
If value of thisLocs is hard-coded in singleRingPolygon.addRing(thisLocs) it works fine, but not the above way.
Not sure why and if you're still having problems, but maybe it will help someone else. I had to use eval(thisLocs) for it to work for me.
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));
}
I'm using OpenLayers with Waze (Maps layers) and having some problems with variables not propagating.
I've got this code:
var lonlat = new Array(), infodiv = new Array();
for (var i = 0; i < stations.length; i++)
{
if (i == 0)
icon_temp = icon;
else
icon_temp = icon.clone();
lonlat[i] = new OpenLayers.LonLat(stations[i].lon,stations[i].lat);
infodiv[i] = "<div style='font-size: 14px;'><strong>" + stations[i].company + "</strong></div>";
marker = new OpenLayers.Marker(lonlat[i],icon_temp);
marker.setOpacity(0.8);
marker.events.register('mousedown', marker, function(evt) {
popup = new OpenLayers.Popup.FramedCloud(null,
lonlat[i],
null,
infodiv[i],
anchor=null,true,null);
map.addPopup(popup);
OpenLayers.Event.stop(evt);
});
markers.addMarker(marker);
}
The code should iterate through the 'stations' array and add markers to the map. It works just fine!
The problem is with the 'lonlat' and 'infodiv' arrays. The 'OpenLayers.Popup.FramedCloud' doesn't see them - it is returned null (checked using FireBug). If I lose the array and only assign each time lonlat = ... and infodiv = ... like this:
for (var i = 0; i < stations.length; i++)
{
if (i == 0)
icon_temp = icon;
else
icon_temp = icon.clone();
lonlat = new OpenLayers.LonLat(stations[i].lon,stations[i].lat);
infodiv = "<div style='font-size: 14px;'><strong>" + stations[i].company + "</strong></div>";
marker = new OpenLayers.Marker(lonlat,icon_temp);
marker.setOpacity(0.8);
marker.events.register('mousedown', marker, function(evt) {
popup = new OpenLayers.Popup.FramedCloud(null,
lonlat,
null,
infodiv,
anchor=null,true,null);
map.addPopup(popup);
OpenLayers.Event.stop(evt);
});
markers.addMarker(marker);
}
it is being propagated to the FrameCloud function and is being shown - but then the problem is it shows only the last lonlat and infodiv (it's like it doesn't hold a copy of them but holds the actual objects - so every iteration 'lonlat' and 'infodiv' are being replaced by the latest info).
How can this be overcome?
This is due to closure of variable i.
Introduce another scope like,
(function(i){
marker.events.register('mousedown', marker, function(evt) {
popup = new OpenLayers.Popup.FramedCloud(null,
lonlat[i],
null,
infodiv[i],
anchor=null,true,null);
map.addPopup(popup);
OpenLayers.Event.stop(evt);
});
})(i);