Error with Leaflet Map - Unable to display tiles on the map - javascript

I am encountering an issue when drawing polygons, point, and line features on a map using the Leaflet.js library.
The polygon is correctly displayed on the map, but the moment I try to draw a point ** or **line, they **disappear **immediately after releasing the mouse click. I need assistance to correct this issue and make the drawing of points and lines on the map functional.
var map = L.map("leaflet-map", {
center: [37.7749, -122.4194],
zoom: 8,
});
let osm = L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}", {
foo: "bar",
attribution: "© OpenStreetMap contributors",
});
osm.addTo(map);
var CyclOSM = L.tileLayer(
"https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png",
{
attribution: "CyclOSM | Map data: © OpenStreetMap contributors",
}
);
CyclOSM.addTo(map);
var Esri_WorldImagery = L.tileLayer(
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
{
attribution:
"Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community",
}
).addTo(map);
let baseLayers = {
"Esri World Imagery": Esri_WorldImagery,
"Open Street Map": osm,
"Cycl OSM": CyclOSM,
};
//Creates three feature groups for points, polygons, and lines on the map
var pointLayer = L.featureGroup().addTo(map);
var polygonsLayer = L.featureGroup().addTo(map);
var lineLayer = L.featureGroup().addTo(map);
var polygon;
var point;
var line;
var allLayers = L.featureGroup([pointLayer, polygonsLayer, lineLayer]).addTo(
map
);
//Add new shapes drawn on the map to the appropriate feature group
map.on("draw:created", function (e) {
var type = e.layerType,
layer = e.layer;
if (type === "point") {
point = layer;
point.addTo(pointLayer);
point.addTo(map);
} else if (type === "polygon") {
polygon = layer;
polygon.addTo(polygonsLayer);
polygonsLayer.addTo(map);
} else if (type === "line") {
line = layer;
line.addTo(lineLayer);
lineLayer.addTo(map);
}
});
var drawControl = new L.Control.Draw({
draw: {
marker: true,
polyline: true,
polygon: true,
rectangle: true,
circle: true,
},
}).addTo(map);

You define 5 types of shapes:
marker, polyline, polygon, rectangle, and circle
but in the feature group, you only catch polyline
To catch makers, you need to change this block:
if (type === "point") {
point = layer;
point.addTo(pointLayer);
point.addTo(map);
to:
if (type === "marker") {
point = layer;
point.addTo(pointLayer);
pointLayer.addTo(map); //add the layer to the map
same for polyline, rectangle and circle.
You can have a look at the Leaflet Draw documentation, you can catch all shapes by not checking for type and directly adding the e.layer from the draw event to the map.

Related

Polygon selection based on marker position in leaflet

On the map, I have an added layer with polygons and one marker on another layer. When I click anywhere, the marker moves to that location and the polygon is selected. The marker has the ability to drag across the map, but just when I drag it, the polygon selection does not appear. How to do this?
var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
});
var map = new L.Map('map', {
'center': [51, 17],
'zoom': 6,
'layers': [osm],
});
var selected;
var marker
marker = L.marker([51, 17], {
draggable: true
}).addTo(map);
var geoJsonLayer2
geoJsonLayer2 = L.geoJson( polygons ,{
style: {
fillColor: "#1ED100",
color: "orange",
fillOpacity: 0.0,
opacity: 0.0,
},
})
.on('click', function (e) {
// Check for selected
if (selected) {
// Reset selected to default style
e.target.resetStyle(selected)
}
// Assign new selected
selected = e.layer
// Bring selected to front
selected.bringToFront()
// Style selected
selected.setStyle({
'color': 'red',
'opacity': 1,
})
})
.addTo(map);
marker.on('dragend', function (e, feature) {
updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});
map.on('click', function (e) {
marker.setLatLng(e.latlng);
updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng);
});
function updateLatLng(lat, lng, reverse) {
if (reverse) {
marker.setLatLng([lat, lng]);
map.panTo([lat, lng]);
} else {
document.getElementById('lat').value = marker.getLatLng().lat.toFixed(10);
document.getElementById('long').value = marker.getLatLng().lng.toFixed(10);
map.panTo([lat, lng]);
document.getElementById("lat").value = lat.toFixed(10);
document.getElementById("long").value = lng.toFixed(10);
}
}
view after clicking on the polygon
view after shifting the marker

How to reset map locator in Leaflet

My map locator works but I am not sure how to reset the marker so that when the user geolocates it resets the position. Currently, my code looks like this:
//map locator
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e) {
var radius = e.accuracy;
L.marker(e.latlng).addTo(map)
.bindPopup("Vous êtes ici").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
map.on('locationfound', onLocationFound);
function onLocationError(e) {
alert(e.message);
}
map.on('locationerror', onLocationError);
// end of geolocator with marker
Overwrite the latlng and radius:
var marker = null;
var circle = null;
//map locator
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e) {
var radius = e.accuracy;
if(!marker){
marker = L.marker(e.latlng).addTo(map);
circle = L.circle(e.latlng,radius).addTo(map);
}else{
marker.setLatLng(e.latlng);
circle.setLatLng(e.latlng);
circle.setRadius(radius);
}
marker.bindPopup("Vous êtes ici").openPopup();
}

Mismatch EPSG4326 tiles and (0, 0) origin point

I am currently trying to create a tile map in Leaflet and I want to be able to sync real life EPSG4326 coordinates in the map but I can't change the location of the map.
In this picture you guys can see where is (0,0) and not in the middle of the map:
and this is my code:
var mapMaxZoom = 6
var mapMinZoom = 0
var mymap = L.map('mapid', {crs: L.CRS.EPSG4326}).setView([0,0], mapMaxZoom);
L.tileLayer('./tiles/{z}/{x}/{y}.png',{
noWrap: true,
minZoom: mapMinZoom,
maxZoom: mapMaxZoom,
tms: true,
}).addTo(mymap);
L.marker([0,0]).addTo(mymap)
.bindPopup('A popup.')
.openPopup();
console.log("map crs: " + mymap.options.crs.code)
mymap.on('click', onMapClick);
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}```

Google Maps with satellite base Map and imageMapType overlay increase zoom

I am displaying an ImageMapType as overlay over a satellite mapType base map.
The base map seems to be limiting the max zoom to 19 in my area, if I change to a Road mapType I get a a couple of more levels. I have high resolution imaginery which I am displaying in the overlay and I want to be able to zoom further. If I use the ImageMapType as base map I can zoom in all I need, but I would really like to display the satellite base map and then continue to zoom into the image even if there's no satellite imaginery available.
Is there any way of accomplishing this? The only thing I can think of is creating a custom base map.
Code is similar to this example https://developers.google.com/maps/documentation/javascript/examples/maptype-image-overlay
Thanks!
My code:
var mapMinZoom = 10;
var mapMaxZoom = 25;
var zoom = 20;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-34.567426059726316, -60.34467143006623),
zoom: zoom,
mapTypeId: google.maps.MapTypeId.SATELLITE,
panControl: false,
streetViewControl: false,
maxZoom: mapMaxZoom
});
createImageLayer('imaginery', 'images')
}
function createImageLayer(key, folder) {
var mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(-34.55771388565057, -60.367219001054764), new google.maps.LatLng(-34.55817334541287, -60.3209562599659));
var imageMapTypeLayer = new google.maps.ImageMapType({
minZoom: mapMinZoom,
maxZoom: mapMaxZoom,
name: key,
getTileUrl: function(coord, zoom) {
if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
return "http://www.maptiler.org/img/none.png";
}
var ymax = 1 << zoom;
var y = ymax - coord.y -1;
var tileBounds = new google.maps.LatLngBounds(
map.getProjection().fromPointToLatLng( new google.maps.Point( (coord.x), (coord.y) ) ),
map.getProjection().fromPointToLatLng( new google.maps.Point( (coord.x), (coord.y)))
);
// write a real condition here, so long this is always valid
if (tileBounds.intersects(tileBounds)) {
return "/static/ui/"+ folder + "/"+zoom+"/"+coord.x+"/"+y+".png";
} else {
return "http://www.maptiler.org/img/none.png";
}
},
tileSize: new google.maps.Size(256, 256)
});
map.overlayMapTypes.push(imageMapTypeLayer)
}
EDIT 1:
Up to now I have managed to overcome this by listening to the zoom_changed event and changing the base map to my imageMapType when the zoom reaches the maximum and back to satellite when the user zooms out. I wonder if there's a cleaner solution to this issue.

How to see coordinates from drawn polygon [duplicate]

This question already has answers here:
How to get point coordinates of a modified drawingManager shape? GoogleMaps API v3
(2 answers)
Closed 9 years ago.
I have an example how to write polygon on google map:
http://jsbin.com/quzed/1/edit
So here is the code:
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
How i can see what are coordinates from drawen polygon, and how to save it (etc. mysql) also how to write polygon if you know coordinates ?
Can sombody help me? I lose in this code? Where is coordinates from user action (user drawing polygon)?
ETC. if I have 3 coordinates (44.5, 55.6) (45.7, 56.87) (46.7, 46.8) how I can draw it here?
And if I draw some polygon on example, how I can see coordinates for polygon?
Look at the example on google's site.
Given you already have that polygon, you can get it's path coordinates with the getPath method.
console.log(bermudaTriangle.getPath() );
There's also a setPath method which would accept an array of coordinates (or an MVCArray for that matter).
Polygons can also have interior rings (as in a donut), but you should get accustomed to simple convex polygons before trying that.
Regarding the question as to "how to save a drawn polygon", Google Maps API provides static functions to encode polygon and polyline paths so you can persist the objects as text.
There are other libraries such as Wicket that can take a Google Maps Object and encode it with a standard WKT format, that is natively understood by geometrical enabled databases.

Categories

Resources