leaflet.js (using geojson data) country labels incorrect - leaflet

I'm using leaflet.js (with geojson) to display a map. [Removing some of the code code to make it more concise].
$.getJSON('./api/map/data', function(data){
let minZoom = 2.25
let defaultZoom = 2.25
let map = L.map('map', {
minZoom: minZoom,
zoomSnap: 0.1
}).setView([43, 0], defaultZoom);
let onEachFeature = (feature, layer) => {
var label = L.marker(layer.getBounds().getCenter(), {
icon: L.divIcon({
className: 'countryLabel',
html: feature.properties.name,
iconSize: [0, 0]
})
}).addTo(map);
};
L.geoJson(data, {
clickable: false,
style: {},
onEachFeature: onEachFeature,
}).addTo(map);
I used this website to download vector maps. Some of the labels are clearly incorrect (and some of them are almost correct). On inspection it seems like some of the lat/longs are not correctly set (or so it seems). Any feedback on how i could make this show up correctly? It would be great if i could come up with labels such that they fit the country borders (meaning maybe add country code wherever necessary).

The problem is connected with your label options. At this moment, your icon position pointing to left top corner of your label and you need to set offset to move label to the center of coordinates. Property that might help you is iconAnchor (see leaflet docs)

Related

Leaflet: how to change map center and zoom level clicking on circleMarker?

I'm working on a map with a few circleMarkers. When a user is clickin on one of this circleMarker, I would like to center the map on this circleMarker and to zoom in. It works when I try this on multipolygon layers, but I didn't succeed on circleMarkers. Does anyone can help me?
Here is the code for my circleMarkers:
<script>
var map = L.map('map', {
center: [41.8, 12.5],
zoom: 5,
zoomControl:true, maxZoom:15, minZoom:4,
});
var feature_group = new L.featureGroup([]);
var raster_group = new L.LayerGroup([]);
var basemap = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri',
});
basemap.addTo(map);
function style1(feature) {
return {
weight: 2,
radius: 10,
opacity: 1,
color: 'black',
weight: 1,
fillOpacity: 1,
fillColor: 'red'
};
}
L.geoJson(villes, {
style: style1,
pointToLayer: function (feature, latlng)
{
return L.circleMarker(latlng).bindLabel( feature.properties.Name, {className: "ville", noHide: true });
}
}
)
.addTo(map)
.showLabel;
</script>.
Here is a link to the complete map.
Thank you.
This can be achieved really simply.
Let's assume marker points to your leaflet marker and map to your leaflet map.
Quick way (recommended)
marker.on("click", function(event) {
map.setView(marker.getLatLng(), 16);
}, marker);
Here, I don't even compute the needed zoom level, because I assume leaflet will have to zoom to its max level anyway.
I could also have added my marker to a L.LayerGroup, even if the main point of a LayerGroup is to group multiple markers.
Anyhow, the more precise way
marker.on("click", function(event) {
map.setView(marker.getLatLng(), map.getBoundsZoom(layerGroup.getBounds());
}, marker);
Note that the quick way will do it nicely too. The second solution might seem more precise but it also slower, and implies a use of LayerGroup which is not the way it has been designed to work (create a new layergroup for each marker).
Don't forget to take yout time reading the docs, it's well-designed and pretty easy to understand.
I find the solution:
function onClick(e) {map.setView(this.getLatLng(),15);}
L.geoJson(villes, {
style: style1,
pointToLayer: function (feature, latlng)
{
return L.circleMarker(latlng).bindLabel( feature.properties.Name, {className: "ville", noHide: true }).on('click', onClick);
}
}
)
.addTo(zoom1)
.showLabel;
Thanks Stranded Kid for your help.

How to apply css on polylines : leaflet

I am working with the application which uses leaflet api.
Introduction
I needed to draw different types of fences, using decorators i can somewhat apply good visuals to the polylines but not much.
Problem
I was willing to show twisted wires instead of dashes, dots or plain lines and I know the twisted wire line will be an image but can't find help about applying custom css to polylines.
Script Example
var fence2Icon = L.icon({
iconUrl: 'xxxx.png',
iconSize: [5, 20]
iconAnchor: [5, 18]
});
// Add coordinate to the polyline
var polylineFence2 = new L.Polyline([], { color: 'red' });
function fencePlace2(e) {
// New marker on coordinate, add it to the map
new L.Marker(e.latlng, { icon: fence2Icon, draggable: false }).addTo(curr);
// Add coordinate to the polyline
polylineFence2.addLatLng(e.latlng).addTo(curr);
var decorator = L.polylineDecorator(polylineFence2, {
patterns:[{offset:5,repeat:'20px',symbol:new L.Symbol.Dash({pixelSize:5})
}]
}).addTo(curr);
}
L.easyButton('fa-flash', function () {
$('.leaflet-container').css('cursor', 'crosshair');
map.on('click', fencePlace2);
polylineFence2 = new L.Polyline([], { color: 'red' });
}).addTo(map);
If someone know anything about polyline or another way please do help.
Thanks for your time:-)
You can add a class in the options of your polyline ...
var polyline = L.polyline(latlngs, { className: 'my_polyline' }).addTo(map);
and add your own settings in the CSS ...
.my_polyline {
stroke: green;
fill: none;
stroke-dasharray: 10,10;
stroke-width: 5;
}
Here is an example: http://jsfiddle.net/FranceImage/9dggfhnc/
You can also access some options directly ...
var polyline = L.polyline(latlngs, { dashArray: '10,10' }).addTo(map);
See Path Options
If you create a polyline you're in fact adding an element to the SVG element which Leaflet uses to draw it's overlays. Styling SVG path elements is different from styling regular HTML elements. There's no such thing as border and background-color etc. It has different properties, if you're interested here's a nice read on the matter:
https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
You can style Leaflet's path elements when you instanciate them via options or via CSS using the properties (related to styling) described in the documentation here:
http://leafletjs.com/reference.html#path
Via options:
new L.Polyline([...], {
weight: 3,
color: 'red',
opacity: 0.5
}).addTo(map);
Via CSS:
new L.Polyline([...], {
className: 'polyline'
}).addTo(map);
.polyline {
weight: 3,
color: red,
opacity: 0.5
}
However, what you want, using an image simply isn't possible. You can use images as fill for SVG paths, but it would be impossible for your usecase. You'de need to add a pattern definition to the SVG Leaflet is using and then you could use that id as the fill property as outlined in this answer:
https://stackoverflow.com/a/3798797/2019281 but will always fill/tile the image horizontally which won't work if your polyline is vertical.

reproject map extent in openlayers 3

I want to set an extend on my Openlayers 3.9.0 map.
When the page loads, I want the map to already be centered in that extend, no matter the layers. So I guess I will set an extend to the view, right?
Map contains a single OSM layer like
var layer = new ol.layer.Tile({
source: new ol.source.OSM(
{
attributions: [
new ol.Attribution({
html: 'All maps © ' +
'OpenCycleMap'
})
]
}
),
opacity: 0.8,
brightness: 0.8
});
Then I set the view
var center = ol.proj.transform([21.54967, 38.70250], 'EPSG:4326', 'EPSG:3857');
var view = new ol.View({
center: center,
zoom: 6,
extent: [2297128.5,4618333.0 , 2459120.25,4763120.0]
});
And then the map
var map = new ol.Map({
target: 'map',
layers: [layer],
view: view,
});
I used my extend in an older project, with EPSG 900913. So to convert the extend from 900913 to default Openlayers 3 3857 I went here here and I put
2297128.5, 4618333 that convereted to 2297128.5,4618333.0
and then
2459120.25, 4763120that convereted to 2459120.25,4763120.0
my two problems
1- the converted coords look similar. Did I do something wrong?
2- the map is centered ok, but not zoomed in the extend. The coords define a county in Greece and the map does not zoom there, I see the whole Greece, along with Turkey and Italy.
What I did wrong? Thanks
Thanks everyone. What I did was
Keep the OSM layer as is.
Define the limits of the county. Turns out it was EPSG 900913
var countyLimits= ol.proj.transformExtent([2297128.5, 4618333, 2459120.25, 4763120], 'EPSG:900913', 'EPSG:3857');
View is now
var view = new ol.View({
center: center,
zoom: 6,
extent : countyLimits,
maxZoom:20
});
map is
var map = new ol.Map({
target: 'map',
layers:[layer],
view: view
});
After the map is defined, fit its view in the limits
map.getView().fit(countyLimits, map.getSize());
//get the view of the map and fit it to the limits, according to the map's size
fitExtend is now deprecated, so I used fit. It is experimental , but I guess it will become standard since it replaced fitExtend.
Thanks anyway people
Sources
OL answer
OL3 API
Several issues:
The extent [2297128.5,4618333.0, 2459120.25,4763120.0] seems to be in EPSG 3857 already and there is no need to transform it.
The extent option of ol.View is experimental and does not seem to work well. You can do the following to set the bounding box (after you declare map):
var extent = [2297128.5, 4618333.0, 2459120.25, 4763120.0];
view.fitExtent(extent, map.getSize());
The initial zoom in your example was due to the zoom level set on the view (zoom: 6). Using fitExtent() should override the initial zoom level. You can remove the zoom, center and extent options from your view declaration.
By the way, regarding the http://cs2cs.mygeodata.eu/ site, it seems that you have to specify EPSG:4326 instead of EPSG:900913 for the input coordinate, for the transformation to work correctly.
Note: ol.View.fitExtent() was renamed to ol.View.fit() in OpenLayers v3.7.0
It can be as easy as:
var min = [2297128.5, 4618333.0];
var max = [2459120.25, 4763120.0];
var extent = ol.extent.boundingExtent([min, max]);
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'osm'})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([21.54967, 38.70250]),
zoom: 3,
extent: extent
})
});
http://jsfiddle.net/jonataswalker/zc3uL66q/

style a geojson point like a POI with leaflet/mapbox

I am using mapbox.js to render a mapbox map. I am trying to load geojson from my server that contain either a country polygon or a city coordinates (lon,lat).
I have been able to style the country polygons but not the city points/markers.
I am not able to modify the geojson to use mapbox simplestyle
Here is the code executed when the page loads (I changed the mapbox map ID):
var southWest = L.latLng(-90, -360), northEast = L.latLng(90, 360);
var bounds = L.latLngBounds(southWest, northEast);
var map = L.mapbox.map('map', 'MapboxMapID', { zoomControl: false, infoControl: true, detectRetina: true, maxBounds: bounds, minZoom: 2, legendControl: {position: 'topright'}});
new L.Control.Zoom({ position: 'bottomright' }).addTo(map);
map.fitBounds(bounds);
var locationsGroup = L.featureGroup().addTo(map);
and then when the user selects a country or city with a selectbox:
$("#select2-search-up").on("change", function (e) {
if (e.added) {
var location = L.mapbox.featureLayer().loadURL('/citiesCountriesID/' + e.added.id).on('ready', function(featLayer) {
this.eachLayer(function(polygon) {
polygon.setStyle({
stroke:false, fillColor:'red', fillOpacity:0.2
});
});
});
locationsGroup.addLayer(location);
} else {
locationsGroup.eachLayer(function (layer) {
if (layer._geojson[0]._id == e.removed.id) {
locationsGroup.removeLayer(layer);
}
});
}
});
Ideally I would like to display a different icon that the standard marker, but I could do with a small red square
Thank you for your inputs
In this example I did some circle markers but I'm pretty sure you can do other basic svg shps or your own .png pretty easy. http://bl.ocks.org/mpmckenna8/db2eef40314fe24e9177
This example from Mapbox also shows how to use a icon from their icon Library which has a lot of choices also. https://www.mapbox.com/mapbox.js/example/v1.0.0/l-mapbox-marker/
It might also help to see some of your geojson structure to see why it can't use simplestyle
In my bl.ocks example I loaded each of the geojson datasets separately
var begin = L.geoJson(start,{
pointToLayer:function(feature, latlng){
return L.circleMarker(latlng,{
radius:9,
fillColor: "orange",
fillOpacity:.7
})
}
})
Is how I set up my circles and I set a different L.geoJson to the other data which I left as the default markers.

Start-Marker from geojson polyline

i have a map with some walking- and bike-routes and popups with a few details an a pic. Now i want to set a marker on the first vertex of a geojson polyline, but i cant find out how. Btw. i´m new to leaflet/mapbox, and i put my map togehter from code snippets.
Here is the map now:
This is how i create the polylines now. I call them via layercontrol.
var mtb = L.geoJson(radjs, {
filter: function (feature, layer) {
if (feature.properties) {
// If the property "underConstruction" exists and is true, return false (don't render features under construction)
return feature.properties.typ === 'mtb';
}
return true;
},
style: {
"color": '#6699cc',
dashArray: '',
"weight": 4,
"opacity": 0.6
}, onEachFeature: onEachFeature2}).addTo(rad);
Thank you for your help,
Marc
You could just add a Feature to your geojson with the latitude and longitude like the do it in the Leaflet GeoJSON Example.
Probably it will be more convenient to read the geometry.coordinates from geojson features and define a new marker.
Beside you have an error on line 569. You should change:
var map = L.mapbox.map('map','',{
to:
var map = L.mapbox.map('map',null,{
Create a simple marker object and add it to the map.
marker = L.marker([0, 0], {
icon: L.mapbox.marker.icon()
}).addTo(map)
Then set the latitude and longitude to the first coordinates of your geoJSON. Assuming your geoJSON is set to the var geojson, you can access the coordinates by indexing into the array.
marker.setLatLng(L.latLng(
geojson.coordinates[0][1],
geojson.coordinates[0][0]))