My code is showing markers from GeoJSON, when I'm haved zoomed into zoom-level 10,it load the GeoJSON-file, but how do I avoid to reput out the same markers?
Is there a way to check if there already exist a marker on a specific place?
The code
map.events.register("zoomend", null, function(){
if(map.zoom == 10)
{
var bounds = map.getExtent();
console.log(bounds);
var ne = new OpenLayers.LonLat(bounds.right,bounds.top).transform(map.getProjectionObject(),wgs84);
var sw = new OpenLayers.LonLat(bounds.left,bounds.bottom).transform(map.getProjectionObject(),wgs84);
var vectorLayer = new OpenLayers.Layer.Vector();
map.addLayer(vectorLayer);
$.getJSON('ajax.php?a=markers&type=json&sw=('+sw.lon+','+sw.lat+')&ne=('+ne.lon+','+ne.lat+')',function(data){
//$.getJSON('test.json',function(data){
var geojson_format = new OpenLayers.Format.GeoJSON({
'externalProjection': wgs84,
'internalProjection': baseProjection
});
vectorLayer.addFeatures(geojson_format.read(data));
});
}
});
Why not use the BBOXÂ Strategy [1] ?
That will do what you need, and will for sure be more performant (it will delete existing features and reload new ones on zoomend). Comparing features to add new will need a lot of comparison, and you can end with too much features on your map.
Check out the js source of the example.
HTH,
1 - http://openlayers.org/dev/examples/strategy-bbox.html
EDIT: if you want to change less code, a call to vectorLayer.removeAllFeatures() before adding will solve your problem… Do you really need to keep features out of bound?
First you would need to get the layer off the map using something like map.getLayersByName. Then you can iterate over layer.features to look for the feature you are adding.
If you can modify the backend to use BBOX, then the BBOX strategy with zoom level and projection settings would take care of a lot for you.
Related
I have a SVG based non geographical layout with image overlay.
var map = L.map('map', {
crs: L.CRS.Simple
});
var bounds = [[0,0], [1000,1000]];
var image = L.imageOverlay('uqm_map_full.png', bounds).addTo(map);
map.fitBounds(bounds);
I traced out different shapes on top of this image.
Now i want to retrieve all the shapes drawn, as a json object array and save it to database. Requirement is to replicate the same shapes later some point by fetching the json object array from database. Is it possible in leaflet.js? I want some thing like below
L.getObjectsArray(map) will give me
var leafletAllShapesConfig = [Object1,Object2,Object3,Object4,Object5]
Now reading the object array i can be able to draw the same shapes like L.draw(leafletAllShapesConfig).
Is this possible and any in built method available to achieve the same? If not please give some idea how can i achieve that.
Yes Leaflet has a built in method: L.GeoJson()
Put your shapes into a featuregroup instead to the map.
var fg = L.featureGroup().addTo(map);
L.marker(latlng,options).addTo(fg);
Then you can get the geojson from the featuregroup:
var gjson = fg.toGeoJSON()
Now you can save this geojson as string with: var str = JSON.stringify(gjson)
To add the shapes back to the map use:
var json = JSON.parse(str);
fg.clearLayers() //To clean the map from the shapes
L.geoJSON(json, {
onEachFeature: function(feature, layer) {
//Code
}
}).addTo(fg);
Now you have your shapes back on your map, but without options/properties like color. GeoJson don't convert them too. You can solve this problem by looping through the layers in the featuregroup and add them manually to the gjson and add the layer.options to the gjson.properties.options and later by adding to the map, read the options from gjson out.
After some research over leaflet.js, i figured out an event "pm:drawend" from "geoman-io/leaflet-geoman-free" plugin Github link https://github.com/geoman-io/leaflet-geoman
map.on('pm:drawend', e => {
console.log(e); //Gives array of all shapes including background image and SVG
});
Above snippet gives me an array of all shapes available(including background image and SVG container), the moment i finish adding any active shape. For reference including the output snippet here which served my purpose.
By default leaflet includes background image as first item. Then follows the SVG container(where my map resides), then all shapes.Hope this will be use to some one else.
I seem to be unable to set a Max Boundary, so that the map bounces back after the user has reached a certain point. Also every time I've tired to change the fitbounds() code the map disappears from my Website.
I've looked at the Leaflet documentation over and over again, with very little luck and been looking through Google for any answers and all the code I have tried has not work. I believe I'm missing or not seeing something really simple.
Any ideas?
If all you want is to restrict the view to a given geographical boundary, the simplest solution is to set the maxBounds option. Unless you want to do it dynamically, in which case the option to use is setMaxBounds. The fitBounds method seems redundant and may actually be the reason why you aren't getting the desired outcome.
var southWest = L.latLng(52.456009,-10.685582);
var northEast = L.latLng(51.699800,5.215615);
var maxBoundArea = L.latLngBounds(southWest, northEast);
var map = L.map('map', {
zoomControl:true,
maxNativeZoom:28,
minZoom:8,
maxBounds: maxBoundArea
});
I would suggest writing a constrain function
function constrain(n,low,high){
return Math.max(Math.min(n, high), low);
}
* Note: I did not think of this myself, it is a function in p5 and thought it might work*
Documentation:
https://github.com/processing/p5.js/blob/0.7.3/src/math/calculation.js#L76
I am new to use this API.
Basically I am developing a widget that calculate freight between two places, so i just need to compute distance only there is no need of showing Map.
If any one has simple explanation please share with me.
I have gone through this link but not able to identify which part of code i need to use for finding distance only.
you can use Geometry computeDistanceBetween()
var placeA = new google.maps.LatLng(-33.873, 151.13);
var placeB = new google.maps.LatLng(-33.92, 151.05);
console.log(google.maps.geometry.spherical.computeDistanceBetween(placeA, placeB));
Reference: https://developers.google.com/maps/documentation/javascript/geometry#SphericalGeometry
I have created a webpage displaying markers on an ersi map using javasvipt.
Data:
MapNorth MapEast
439624 504743
439622 504736
439722 504775
439738 504739
439715 504774
439734 504739
The javascript code:
var points = data.map(function(x){
return [x.MapEast, x.MapNorth];
});
var myMultiPoint = {"geometry":{"points":points,"spatialReference":27700},"symbol":{"color":[255,255,255,64],
"size":6,"angle":0,"xoffset":0,"yoffset":0,"type":"esriSMS","style":"esriSMSCircle",
"outline":{"color":[0,0,0,255],"width":6,"type":"esriSLS","style":"esriSLSSolid"}}};
var gra = new esri.Graphic(myMultiPoint);
myMap.graphics.add(gra);
var graExtent = esri.graphicsExtent(myMap.graphics.graphics);
myMap.setExtent(graExtent);
What the above code does is plot markers on the map and then zooms into the extent. What my employers want now is for me to find the central point of all of those points and display one marker in the center.
Can this be done? If so and you tell me how?
Thanks
Paul
Couple of things.
Did you know about gis.stackexchange.com? They might better solve your problem.
What you're trying to do is find the centre of a polygon assuming those points aren't all in a line.
Here's a link with an answer to the question I think you're asking https://gis.stackexchange.com/questions/7998/how-can-i-calculate-the-center-point-inside-a-polygon-in-arcgis-9-3
The solution posted there uses getExtent().getCenter() as seen here
var myPolygonCenterLatLon = myPolygon.getExtent().getCenter();
I think what you want to be doing here is instead of creating a Multipoint, create a Polygon from your array of points. Once you have a polygon defined, you can do something like
var myPolygon = new Polygon(points);
var centroid = myPolygon.getCentroid();
This should get you the centroid of the points making up the Polygon.
https://developers.arcgis.com/javascript/jsapi/polygon-amd.html
Note that this requires at least version 3.7 of the JS API, though.
One thing to point out to those trying to using .getCentriod() , make sure your polygon is closed. Your 1st point and Last Point need to be in the same spot. Otherwise it wont work right. ( I ran into this a year ago, not sure if they changed this)
I'm new to ESRI's JavaSCript API and am very impressed by its ease of use and speed. As part of a interactive data portal I have users enter latitude and longitude as decimal degrees as part of a spatial query to return State, County and FIPs. That part works just fine, but as an added feature I want to draw a dot graphic on an existing map showing the entered coordinates location (DONE) then Center and Zoom to said point at some reasonable scale.
The centerAndZoom method is the logical choice here, but it doesn't seem to be working. My sense is that the Map needs to be refreshed but I can't seem to figure this one out.
I'm sure I'm missing something fundamental here; Thanks in advance for your time!
function DrawPointAndZoom() {
// Get currently entered lat/long.
var lat = $('#SiteLatitude').attr('value');
var long = $('#SiteLongitude').attr('value');
var latLongPoint = new esri.geometry.Point(long, lat, new esri.SpatialReference({ wkid: 4326 }));
//Draw point
var symbol = new esri.symbol.SimpleMarkerSymbol().setSize(8).setColor(new dojo.Color([255, 0, 0]));
var graphic = new esri.Graphic(latLongPoint, symbol);
var infoTemplate1 = new esri.InfoTemplate();
infoTemplate1.setTitle("point1");
infoTemplate1.setContent("test point 1");
graphic.setInfoTemplate(infoTemplate1);
map.graphics.add(graphic);
map.centerAndZoom(latLongPoint, 15);
}
95% of the time, anything that doesn't work with a Point in the JS API is due to the spatialreference being wrong. :)
Check that your map's SR (map.spatialreference.wkid) is the same as the point's (4326, as you've defined it here.) You may need to use everyone's favourite function, geographicToWebMercator if the map is using one of its usual Web Mercator coordinate systems.
Edited with details from Tony's comment/answer:
var webMercPoint = esri.geometry.geographicToWebMercator(latLongPoint)
{Missing code here}
map.centerAndZoom(webMercPoint, 15);
Yes! thanks for taking the time to respond. I went down that hole yesterday and tried it with a webMercatorPoint... and viola it worked!
var webMercPoint = esri.geometry.geographicToWebMercator(latLongPoint)
{Missing code here}
map.centerAndZoom(webMercPoint, 15);
Much Appreciated!