Setting a Max Boundary is not working Leaflet - javascript

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

Related

Getting a central point from an esri multipoint with javascript

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)

Mapbox.js set map default zoom option

I have a mapbox.js map but the parameter zoom doesn't seem to be doing anything
and I can't figure it out in the documentation. whatever I set zoom to the zoom level always defaults to my project zoom level Here is the code:
<script src='https://api.tiles.mapbox.com/mapbox.js/v1.6.1/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v1.6.1/mapbox.css' rel='stylesheet' />
$(document).ready(function() {
var map = L.mapbox.map('map', 'nhaines.hek4pklk', {
zoom: 1
});
// disable drag and zoom handlers
map.dragging.disable();
map.touchZoom.disable();
map.doubleClickZoom.disable();
map.scrollWheelZoom.disable();
// disable tap handler, if present.
if (map.tap) map.tap.disable();
});
It took me a lot of digging around but I figured this out on my own. The dev's didn't respond yet. We were going about this all wrong. Here's what to do:
First, create the MapBox object, but set zoomAnimation to false. This question helped me realize that trying to setZoom while a CSS3 animation was in progress wouldn't ever work because it's tough to break out of. At least that's what I think is going on. Setting zoomAnimation to true allows the map to animate in and bypasses any custom zoom levels, so clearly this is very important.
var map = L.mapbox.map('map', 'username.map_id', {
zoomAnimation: false
});
Next, create a polygon layer and add to map from map's geojson. You find this within your MapBox projects > info tab. (In my case this geojson happens to contain the lat/lng coords of a polygon but your case may be different. featureLayer() should still add the geojson either way.)
var polygonLayer = L.mapbox.featureLayer().loadURL('http://your/maps/geojson').addTo(map);
After polygon layer (or whatever your lat/lng coords are of) has been added to map
polygonLayer.on('ready', function() {
// featureLayer.getBounds() returns the corners of the furthest-out markers,
// and map.fitBounds() makes sure that the map contains these.
map.fitBounds(polygonLayer.getBounds());
map.setView(map.getCenter(), 10);
}
Apparently fitBounds satisfies the map requirements to allow setView to be called on it, since now you can just call the map object directly to get the center lat/lng.
I haven't tested this in simple cases - I adapted this code from mine which checks if an address's lat/lng coords fall within a polygon while iterating over a series of MapBox maps. It should get you going though. Hope it helps!

ArcGIS JavaScript API (3.8) centerAndZoom does not appear to be working

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!

map.setZoom() is not working but map.setCenter() is working

Part of my code looks like this, I am able to center the map using
map.setCenter(myLatlng);
but after that I am trying to zoom the map
marker_id = id;
marker_id = new google.maps.Marker();
marker_id.setIcon(image);
myLatlng = new google.maps.LatLng(loctionupdateobj[id].lat, loctionupdateobj[id].lang);
marker_id.setPosition(myLatlng);
marker_id.setMap(map);
map.setCenter(myLatlng);
alert(map.getZoom());
map.setZoom(10);
alert("game again " + map.getZoom())
You can see the
alert("game again " + map.getZoom())
in the code it is giving me an alert like game again 10 but the zoom level is never going to 10.
But the first alert is 4 (which I set during initialsation).
As I am not able to setZoom, I am creating a new map instance each time when I am adding new markers.
Finally found !!!
The previous programmer who coded my project wrote a line
google.maps.event.clearListeners(map);
So the second alert is retuning 10, what is the first alert returning, is this 10 too?
If so you're zoom is already 10 (sorry if it's a stupid question, but no mention of this).
My map works with the places api and is looking for a location.
I first initialize my map with zoom : 23.
Once I search and submit my location the map defaults to its original zoom. So i had to use map.setZoom(23), It was working at first then just stopped.
It's strange because map.fitBounds() works perfectly.
setTimeout(function(){
map.setZoom(23);
console.log('zoomed');
},1);
My dirty solution for the time being. ¯\_(ツ)_/¯
To solve this issue, you can try calling the setZoom method after all the markers have been plotted on the map and all the other methods such as setCenter, bounds.extend are called. So u have to call setZoom method in the last marker function.

LatLong falls within a given polygon in D3 + Leaflet

I am trying to learn how to use the Javascript library leaflet along with d3 to create various map visualisations.
I have been following this tutorial which creates a choropleth map of the United States with some interactivity. This provides some of what I need, but the main functionality I want is to have a list of lat/long coordinates classified according to which region they belong to.
This would mean, in the tutorial map for example, if I had a lat long value (55, -3) which fell within the state of Arizona's polygon, the program could classify this point as belonging to Arizona.
Is there a function in the leaflet (or d3) library which will allow me to enter a lat long coordinate as a parameter and return the name of the feature it belongs to? The tutorial above allows you to attach a function to every feature via the onEveryFeature property and can fire mouseover events when each feature is hovered over. Surely there is a way to extend this functionality to numerically entered data instead of mouse points?
Leaflet would need some tweaking if you wish to do this. It leaves the handling of mouseclicks to the browser and therefore does not need logic for determining if a point lies inside a polygon.
I am not very knowledgeable about d3 but it's not glaringly obvious to me how it'd do this out of the box. Looking at the polygon code, I do find a clipping algorithm and intersection of infinite lines.
If you add a third library, however, this should be rather simple.
The OpenLayers Geometry library can determine if a point lies inside a polygon.
EDIT: I got this to work, see also http://jsfiddle.net/VaY3E/4/
var parser = new OpenLayers.Format.GeoJSON();
var vectors = parser.read(statesData);
var lat = 36;
var lon = -96;
var point = new OpenLayers.Geometry.Point(lon, lat);
for( var i = 0; i< vectors.length; i++ ){
if(vectors[i].geometry.intersects(point)){
alert(vectors[i].attributes['name']);
}
}
Or you could use https://github.com/maxogden/geojson-js-utils , a bit more specific library. It looks like it knows how to read GeoJSON and it has a method gju.pointInPolygon. I've not tested it though.

Categories