Leaflet map: how to removeLayer and add popups to the map? - javascript

I'm trying to addLayer (marker, circle and popup) to the map.
I am able to add the marker and circle successfully but I cannot add the popup and also I cannot removeLayer which result in multiplying the marker and circle...
It basically doesn't remove the previous marker and circle before adding the new one in.
This is a working FIDDLE:
https://jsfiddle.net/31ws6z37/3/
And this is my entire code:
function initializeMapAndLocator(){
var map = L.map('map_2385853');
googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo(map);
map.locate({setView: true,
maxZoom: 16,
watch:true,
timeout: 60000
});
function onLocationFound(e) {
var radius = e.accuracy / 2;
var marker = new L.Marker(e.latlng, {draggable:true});
var circles = new L.circle(e.latlng, radius).bindPopup("You are within " + radius + " meters from this point").openPopup();;
map.removeLayer(marker);
map.removeLayer(circles);
map.addLayer(marker);
map.addLayer(circles);
}
map.on('locationfound', onLocationFound);
}
initializeMapAndLocator();
Could someone please let me know how to removeLayer and also how to add the popup to my map?
Any help would be appreciated.
EDIT:
Nothing seems to be working and I'm pulling hair out. Every corner I turned and every search indicates that I need to use the removeLayer to remove the marker but this is not the case for me and I don't understand it!!
This is another version of my code and still adds markers before removing the old one....
var map = L.map('map_2385853');
googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
}).addTo(map);
map.locate({setView: true,
maxZoom: 16,
watch:true,
timeout: 60000
});
function onLocationFound(e) {
var radius = e.accuracy / 2;
var marker;
var circles;
marker = new L.Marker(e.latlng, {draggable:true});
circles = new L.circle(e.latlng, radius);
//var pop = new bindPopup("You are within " + radius + " meters from this point").openPopup();
map.eachLayer(function (layer) {
map.removeLayer(marker);
map.removeLayer(circles);
});
map.addLayer(marker);
map.addLayer(circles);
}
map.on('locationfound', onLocationFound);
I'm sure I'm doing something wrong but I just don't know where and how!
Any help would be great.

The problem is that you a mixing the wrong stuff together. It would be easier for you to learn the basics creating a leaflet map. In your first snippet you first initialize the marker, then remove it and the you add it to your map. That make no sense and isn't logical. Ask in the onLocationFound() function if the marker and circles layers are on the map. If true then remove it:
var marker;
var circles;
function onLocationFound(e) {
var radius = e.accuracy / 2;
if(map.hasLayer(circles) && map.hasLayer(marker)) {
map.removeLayer(circles);
map.removeLayer(marker);
}
marker = new L.Marker(e.latlng, {draggable:true});
circles = new L.circle(e.latlng, radius);
circles.bindPopup("You are within " + radius + " meters from this point").openPopup();
map.addLayer(marker);
map.addLayer(circles);
}
Here is a the modified FIDDLE. Hope it helps
greez Manuel

Related

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.

Horizontal repeating Google Maps Marker on ImageMapType

<!DOCTYPE html>
<html>
<head>
<title>Image map types</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var moonTypeOptions = {
getTileUrl: function(coord, zoom) {
var bound = Math.pow(2, zoom);
return 'full-out' +
'/' + zoom + '/' + coord.x + '/' +
(bound - coord.y - 1) + '.png';
},
tileSize: new google.maps.Size(256, 256),
maxZoom: 6,
minZoom: 1,
radius: 1738000,
name: 'Moon'
};
var moonMapType = new google.maps.ImageMapType(moonTypeOptions);
function initialize() {
var myLatlng = new google.maps.LatLng(0, 0);
var mapOptions = {
center: myLatlng,
zoom: 1,
streetViewControl: false,
mapTypeControlOptions: {
mapTypeIds: ['moon']
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.mapTypes.set('moon', moonMapType);
map.setMapTypeId('moon');
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I have above code to render a custom large 16834 * 16834 image of 19 mb which is broken into tiles using gdal2tiles and gdal_translate. In short, I have all the corresponding tiles.
The above code is working perfectly fine rendering image and different zoom levels. However, when I add marker, it is displayed multiple times at lower zoom level. I would like the marker not repeat itself horizontally.
Is there any way to avoid horizontal repeating markers? Currently, I'm using Leaflet.js which doesn't repeat marker horizontally as Google Maps library.
I want to use Google maps because of its stability and popularity.
I'm using Ubuntu 14.04 as OS.
set the optimized-option of the markers to false
For those who has still this problem, have a look at my solution.
1- Set the maps zoom to (2) and add marker positions (lat,long) i.e
var minZoomLevel = 2;
map.setZoom(minZoomLevel);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < result.length; i++){
var latlng = new google.maps.LatLng(result[i].Lat, result[i].Lng);
bounds.extend(latlng);
});
2- Attach a event listener on zoom changed i.e
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
3- Attach a center changed listener (This done the trick) i.e
google.maps.event.addListener(map, 'center_changed', function()
{
checkBounds(bounds);
}
function checkBounds(allowedBounds) {
if(allowedBounds.contains(map.getCenter())) {
return;
}
var mapCenter = map.getCenter();
var X = mapCenter.lng();
var Y = mapCenter.lat();
var AmaxX = allowedBounds.getNorthEast().lng();
var AmaxY = allowedBounds.getNorthEast().lat();
var AminX = allowedBounds.getSouthWest().lng();
var AminY = allowedBounds.getSouthWest().lat();
if (X < AminX) {X = AminX;}
if (X > AmaxX) {X = AmaxX;}
if (Y < AminY) {Y = AminY;}
if (Y > AmaxY) {Y = AmaxY;}
map.setCenter(new google.maps.LatLng(Y,X));
}
Every time you change the center, it will check your points and restrict map to certain area . Setting zoom will show only one world tile, and check bound will restrict the horizontal scrolling, thats how your markers will show only one time in map, set zoom according to your condition that fits in !!

TileMill MapBox map pans to different world without any markers

I have a map I exported from tilemill, made a mapbox map and threw some points on it. The view starts off looking at the US, with a marker somewhere in the middle. If I pan left until the next time I see the US, the markers are gone. Here's the code minus the geoJson data.
var map = L.mapbox.map('map', 'natecraft1.xdan61or').setView([-102, 39], 4);
map.markerLayer.on('layeradd', function(e) {
var marker = e.layer;
var feature = marker.feature;
var image = feature.properties.images
// var img = images
// Create custom popup content
var popupContent = '<img class="pics" src="' + image + '" />'
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 320,
offset: [180, 20]
});
});
map.markerLayer.setGeoJSON(geoJson);
map.markerLayer.on('click', function(e) {
e.layer.openPopup();
var lat = e.layer.getLatLng().lat;
var lng = e.layer.getLatLng().lng;
map.panTo([lat+5, lng+5], 2);
});
map.markerLayer.on('', function(e) {
e.layer.closePopup();
});
Your tilelayer is wrapping around the globe for coordinates outside of the (-180, 180) range. Best option is to set the maxBounds option so users don't pan outside of that map and just get bounced back.
var map = L.mapbox.map('map', 'examples.map-9ijuk24y').setView([0,0], 2);
var layer = L.mapbox.tileLayer('examples.map-9ijuk24y', {
noWrap: true,
minZoom: 3
}).addTo(map);
map.options.maxBounds = map.getBounds();
Here's a live demo of what that would look like

Google maps V3: prevent marker scaling

I have a google map, and an marker on it.
I need the marker to be a fixed size of, for example, 10x10 pixels, and remail the same even if i zoom in or zoom out.
This is what i have right now (and is not workig):
var marker = new google.maps.Marker({
position: circleCenter,
map: googleMap,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillOpacity: 0.5,
fillColor: 'ff0000',
strokeWeight: 10,
size: 5
}
});
Is this possible to block the marker of scaling it's size when the map zoom is changed?
Google does not have a out-of-box way to stop markers from scaling.
You could use a Ground Overlay to set a fixed area on the map and then attach an image. The trick with ground overlays is you have to know the coordinates of the bounds object and you probably will have to come up with some way of calculating the bounds. In this example I just expand a center point into a rectangle.
You would also loose other marker capabilities since this method doesn't use a marker object (e.g. dragging, animations, etc.), but the overlays do have click events.
Here is a proof of concept: http://jsfiddle.net/bryan_weaver/4rxqQ/
relevant code:
function initialize() {
var map;
var centerPosition = new google.maps.LatLng(38.713107, -90.42984);
var options = {
zoom: 9,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map')[0], options);
var icon = 'https://www.google.com/mapfiles/marker_black.png';
var iconBounds = constructBounds(38.713107, -90.42984);
var staticOverlay = new google.maps.GroundOverlay(icon, iconBounds);
staticOverlay.setMap(map);
}
function constructBounds(lat, lng){
var sw = new google.maps.LatLng(lat - .03, lng - .025)
var ne = new google.maps.LatLng(lat + .03, lng + .025)
return new google.maps.LatLngBounds(sw, ne);
}

Drawing line (freeform) on Google maps?

Hi I want to draw a line (free-form, Photoshop pencil / paintbrush style) over Google maps.
What would be the best way to do it?
How complicated would it be to do this AND keep the zoom option (so that line scales / disappears when the map is scaled)?
Which would be the best library to use for that (canvas? svg? something else)?
You could use the built indrawing tools, but if I recall correctly, you would need to click quite a bit to get a free form line.
Here's another pretty rough idea. Capture the mouse coordinates of the map container, grab the latLng from a google.maps.MapCanvasProjection and push the coordinates to a polyline path.
var map;
var elevator;
var myOptions = {
zoom: 6,
center: new google.maps.LatLng(46.87916, -3.32910),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map')[0], myOptions);
var markers = [];
var isDrawing = false;
var overlay = new google.maps.OverlayView();
overlay.draw = function () {};
overlay.setMap(map);
// Add a listener for idle event and call getElevation on a random set of marker in the bound
google.maps.event.addListener(map, 'click', function () {
var polyLine = new google.maps.Polyline({
map: map
});
$("#map").mousemove(function (e) {
var pageX = e.pageX;
var pageY = e.pageY;
var point = new google.maps.Point(parseInt(pageX), parseInt(pageY));
var latLng = overlay.getProjection().fromDivPixelToLatLng(point);
polyLine.getPath().push(latLng);
});
});

Categories

Resources