I am using leaflet.js to create few markers and circles. I am using the below given code to draw circles : -
L.circle([ lat, lng ], 1000, {
color : colorCode,
stroke : false,
fillColor : colorCode,
fillOpacity : 0.7
});
Now if I edit this circle on UI and drag this circle vertically downwards, the circle size increases and vice a versa. Similar issue is with calling the above given method with different lat lngs. The same radius (1000) sized circle get plotted with different sizes on map.
My requirement is to place marker with same radius with same size on map everywhere.
I checked L.circleMarker but it takes radius in pixels and also circleMarkers does not scale in zoomin zoomout events. That is why I can't use circleMarkers.
I changed the crs option to 4326 but no success. I am using imageOverlay not tileset. I have created a fiddle.
http://jsfiddle.net/newBee_/88bdrzkr/12/
Try creating a circle on top area then edit and move it downwards. It's size increases. This is what I want to stop. This will resolve the problem of generating circle of same radius via code in different area of map with same size. Please help.
Please suggest.
Edit:
It looks like this is a bug deep into Leaflet 0.x: L.Circle radius computation uses hard-coded Earth projection rather than the specified CRS. Leaflet 1.0 seems to correctly check for the CRS before using the Earth-related computation.
For your case, simply overriding the faulty method seems to fix it, at least visually.
Demo: http://jsfiddle.net/88bdrzkr/13/
The "corrected" method to include in your script:
L.Circle.include({
_getLngRadius: function () {
return this._getLatRadius();
}
});
Regarding iH8's answer, the trick to override L.CRS.Simple.scale is similar to highly zooming (the 256 factor expands the latLng to much further pixels - any high number will do). At high zoom, you are moving your circle along a very short distance, for which the latitude does not change much. So you do not see any visible difference in radius, even though the bug is still there.
Demo of using just higher zoom, no method override at all: http://jsfiddle.net/kau6g8fk/1/
For your need where the circle looks to be more like a visual aid, any of these 3 solutions is enough.
Edit: the CRS is not the issue at all.
Previous message:
If you use Leaflet for indoor mapping, as your jsFiddle suggests (or any flat type map, as opposed to the projection of a sphere like Earth on to a plane), you could simply use L.CRS.Simple
Striked out this faulty solution as pointed out by Ghybs in his answer
Very weird issue, turns out that overloading L.CRS.Simple's scale method to return 256 * Math.pow(2, zoom) fixes this. Here's a fork of your JSFiddle: http://jsfiddle.net/kau6g8fk/ I'm unsure as to the cause of this issue, it would require more research. Will do if i find the time. Found the solution here: http://codepen.io/mike_beweb/pen/BymKGe
The answer below was given before the poster edited his/her question and showed that the used CRS was L.CRS.Simple while i presumed the default CRS. I'll leave it in tact because it might come in handy for some users:
The size change on drag of your L.Circle's is because of your map's default spherical mercator projection (EPSG:3857). Best explained with an image, here's a map with a graticule overlay on every 10 degrees:
Demo on Plunker: Leaflet 0.7.5 EPSG:3857 Spherical
As you move further from the equator every plane becomes higher. Thus your circle automaticly becomes higher the further north/south you drag it. You could use a equirectangular projection (EPSG:4326), in which every plane has the same size regardless of the distance from the equator:
Demo on Plunker: Leaflet 0.7.5 EPSG:4326 Equirectangular
With equirectangle projection you won't have the problem you're having now but you'll have to change your tileset to one with EPSG:4326 projection and those are hard to come by compared to EPSG:3857 tilesets.
If you're not willing or unable to change projection another solution could be to hack around L.CircleMarker and change the radius of your markers depended on current zoomlevel. But that's rather ugly in my opinion.
Related
I have played around with the d3js (v5) maps,
i'm trying to generate this map (the screenshot was taken from a random website),
For my particular case there is no need to present Antarctica.
I have read the documentation here: https://github.com/d3/d3-geo#projections,
and followed the instructions and used geoMercator, got this flat map which gets cutoff in the top north for some reason.
What is the correct approach for getting the first map's layout?
any suggestions?
The projection you are looking at is a Mercator projection.
With d3.geoMercator(), the scale value is derived from the circumference of the cylinder that forms the projection surface. The scale value is the number of pixels per radian. The default value anticipates stretching the 360 degrees of the cylinder over 960 pixels: 960/Math.PI/2.
For vertical angular distances, there is no such scaling factor, as one moves to extreme longitudes, the angular distance between points is increasingly exaggerated, such that the poles will be at ± infinity on the y axis. Because of this Mercator's, especially web Mercator's are often truncated at ±~85 degrees. With an extent of [-180,85] and [180,-85], a Mercator is square.
This limit is incorporated into d3-geoMercator, which "Defines a default projection.clipExtent such that the world is projected to a square, clipped to approximately ±85° latitude. (docs)"
This means that if we want to show the full extent of a d3-geoMercator, across 960 x 960 pixels, we can use:
d3.geoMercator()
.scale(960/Math.PI/2) // 960 pixels over 2 π radians
.translate([480,480]) // the center of the SVG/canvas
Which gives us:
The default center of d3-geoMercator is [0°,0°], so if we want [0°,0°] to be in the middle of the SVG/canvas, we translate the center so that it is in the middle, with a translate of [width/2,height/2]
Now that we are showing the whole world, we can refine to show only the portion we want. The simplest method might just be lopping off pixels from the bottom of the svg/canvas. Using the above code with a canvas/svg height of 700 pixels (and keeping 960 pixels across, using the same scale and translate) I get:
I did not remove Antarctica from this image - it just happens that it is cut off without having to filter it out (this is not necessarily ideal practice: it is still drawn).
So, an SVG/Canvas with width 960, height 700, with a projection scale of 960/Math.PI/2 and a translate of [480,480] appears to be ok. These values will scale together for different view port sizes.
With maps, there is often a lot of eyeballing to get the visual effect desired, tweaking projection.translate() or projection.center() can help shift the map to the desired location. But we can do this computationally. I'll speak to one method here, using projection.fitSize() (though this won't solve the required aspect ratio without extra steps).
Project.fitSize([width,height],geojson) takes an array specifying the dimensions of the SVG/canvas and a geojson object and tweaks the projection scale and translate values so that the geojson feature is contained in the SVG/canvas. The geojson feature could be a bounding box of the part of the world you want to show, so you could use:
projection.fitSize([width,height], {
type: "Polygon",
coordinates: [[
[-179.999,84] ,
[-179.999,-57] ,
[179.999,-57] ,
[179.999,84],
[-179.999,84]
]]
})
Where ~84 degrees north is the north end of Greenland and ~56 degrees south is roughly the tip of South America. This will ensure that the entire portion of the world you want to see is visible. However, as noted above, this doesn't consider aspect, so if you constrain the above extent to square dimensions, you'll still be showing the full extent of the Mercator.
How would I go about fixating the viewport on a D3 (v4) map, such that users cannot zoom and pan outside of this viewport? Say I wanted to fix the viewport on South East Asia, and that my starting point is this fiddle. So pseudo code would be something like:
...constrainViewport([[x0,y0],[x1,y1]])
where x0,y0,x1 and y1 are the coordinates of the bounding viewport rectangle.
I have seen the following block from Sean Connelley however the solution presented is very complicated and out of date (v3). Happy to say I don't understand what is going on there either. Is there really no better (or 'native') way to achieve this result?
You can do this with zoom.translateExtent([a,b]) where a is a coordinate representing the top right and b is a coordinate representing the bottom left of the panning extent (it will constrain zoom when zooming out too).
Since you are working with geographic data, you can set your limits fairly easily in degrees of latitude and longitude:
// extent bounds (arbitrarily chosen)
var topLeft = projection([-180,80]);
var bottomRight = projection([0,-20]);
zoom.translateExtent([topLeft,bottomRight])
Here's an updated fiddle.
I want to display objects on a map in their exact dimensions.
I have reference data about these objects, containing the length and width of the object in meters, now I need to convert the meters into pixels for the leaflet icon size based on the zoom level.
var meterlength = 50;
var meterwidth = 40;
//convert meters to pixels
var icon = L.divIcon({html:"<svg>..</svg>",iconSize:[xx,yy]});
I found this https://github.com/makinacorpus/Leaflet.GeometryUtil/
GeometryUtils with the length and distance function, but could not get it working.
Any ideas ? Thank you very much !
EDIT:
This answer solved my original problem:
https://gis.stackexchange.com/a/198444
But I'm sacling the icons on map zoom using the "zoomanim" event - unfortunately the map.containerPointToLatLng() Methode applies to the old zoom level not to the new one.
Is there a Workaround ?
If you want your image to represent the object real size, then you should probably better use an L.imageOverlay instead of a marker and trying to adjust its size based on zoom level.
See https://gis.stackexchange.com/questions/171609/resize-divicons-svgs-at-zoom-levels-leaflet
Then you would need to find the appropriate coordinates for your Image Overlay bounds, not pixels.
Now if you really want to change your marker icon size depending on the zoom level, you have several posts on SO and GIS SE that cover this topic.
E.g. Best way to make marker resizable in leaflet
Is it possible to get the current scale value of the Leaflet component?
The image above shows "300 km" or "100 miles" that i would like to retrieve by a method. The existing documentation does only show how to add the scale control with specific options: http://leafletjs.com/reference.html#control-scale
Be careful with the scale at low zoom levels (when you see a large portion of the world).
The scale that you see is actually valid for the center horizontal line of your map view. It is even slightly wrong for the corner of the map, where it is placed!
If you just want to "duplicate" that visual scale somewhere else, you could simply create another Scale Control and extract its HTML container instead of embedding it to your map:
document.getElementById("myNewContainerId").appendChild(
L.control.scale(options).onAdd(map)
);
If you want to read the actual pixel length and text of the Scale Control, you could retrieve them through the internal _mScale.style.width and _mScale.innerHTML properties of the Scale Control. Replace _mScale by _iScale if you want the imperial values instead of the metric ones.
Otherwise, if you want to be able to measure some distance between 2 points on the map, you should rather use the myLatLng.distanceTo(otherLatLng) method, which would be far more accurate, as it would not only use the correct scale at the myLatLng actual latitude, but also correct for the possible different scale along the path to otherLatLng if it is placed at a different latitude.
Returns the distance (in meters) to the given LatLng calculated using the Haversine formula. See description on wikipedia
I would like to ask how do I check if a certain Polyline passes thru a Circle? In the image below, the red polyline passes inside the green circle. I know it is possible to determine if a marker is within a circle but i don't know how to do it or if it is feasible for polylines.
I still have 8 reputation points so I can't post images, here's the link to the image: http://i.stack.imgur.com/0fzXu.png
Thanks in advance! :)
I'd probably do the following:
Get bound of circle.
Filter the polyline coordinates and find the points that fall into that bound.
Calculate distance between circle center and each of those points. (circle/bound center can be easily obtained by some built-in method)
If any distance < circle radius, it gives you result.
Only problem with this algo is, if your polyline goes through the circle but your list of popyline coordinates does not contain one that falls in the bound. I haven't come up with a solution for that yet :)