Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet: Circle behaving different from CircleMarker

In the documentation for Leaflet here: http://leafletjs.com/reference-1.2.0.html#circlemarker it says that CircleMaker extends Circle, and that it is the same thing, except the radius is specified in pixels rather than in meters, so that the circles stay constant size even if you zoom the map.

I do however need Circles, because I am trying to draw 100m radius circles on a map. To do this, I use the following code:

var geojsonLayer = new L.GeoJSON(null,{
pointToLayer: function (latlng){
    return new L.CircleMarker(latlng, {
        radius: 5,
        fillColor: "#ff7800",
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8,
    });
}});

map.addLayer(osm);
map.addLayer(geojsonLayer);
geojsonLayer.addGeoJSON(jsonExample);

This works perfectly, however, if I change the code to use "Circle" instead of CircleMaker the entire map fails to load, and I get a javascript error:

Error: Error: Invalid LatLng object: (56.229917, NaN)

I can fix this by pre-filtering the geojson to remove those points which lack both latitude and longitude, but I'm confused: Circle and CircleMaker both specify that they take a LatLng-object as the specification of the center-point, I don't get how a certain LatLng object can be valid as centre-point for a CircleMarker, but invalid if used as the centerpoint for a Circle.

Am I overlooking something obvious, or is this just a weakness and/or bug in Leaflet that I'll just have to work around ?

like image 323
Agrajag Avatar asked Aug 15 '12 09:08

Agrajag


3 Answers

I fixed this by changing the _getLngRadius() method of leaflet.js in L.circle. In leaflet version 0.4.4, it's around line 4913.

This method differs from the one in circleMarker, as it computes the radius of the circle dynamically. If you change the line that has

this._mRadius/hLength

to

this._mRadius.radius/hLength

it should be ok.

like image 181
Antonis Anastasiadis Avatar answered Nov 07 '22 21:11

Antonis Anastasiadis


There is no problem with the code anymore. Though this same issue can arise easily because of the different constructors:

L.CircleMarker( <LatLng> latlng, <Path options> options? )

and

L.Circle( <LatLng> latlng, <Number> radius, <Path options> options? )

Be sure to pass the radius to your new circles.

like image 39
Marcel Pfeiffer Avatar answered Nov 07 '22 22:11

Marcel Pfeiffer


You can add if(latlng && latlng.lat && latlng.lng) at the begining of your function (latlng)

that will ignore the faulty datas.

like image 20
JulienFr Avatar answered Nov 07 '22 22:11

JulienFr