I am trying to change the opacity of the zoom control buttons that I have positioned at the top right of my leaflet map. I tried doing "mymap.zoomControl.setPosition('topright').setOpacity(0.5);" in the last line but it causes the whole map to disappear when I load the page. If you know the code to change the opacity of the zoom buttons on the map such that users are able to see through do let me know.
var southWest = L.latLng(-89.98155760646617, -180), northEast = L.latLng(89.99346179538875, 180);
var bounds = L.latLngBounds(southWest, northEast);
var mymap = L.map('map', {
center: [20.594, 78.962],
maxBounds: bounds, // set max bounds for the world map
zoom: 4, // default zoom level when the web is initiated
zoomSnap: 0.25, // map's zoom level must be in multiple of this
zoomDelta: 0.25, // controls how much the map's zoom level will change after a zoom
minZoom: 3.25, // min zoom level the user can zoom out
maxZoom: 6, // max zoom level the user can zoom in
zoomControl: true, // allow zooming
});
mymap.zoomControl.setPosition('topright'); // set + and - zoom buttons to top right corner .setOpacity('0.4')
var MapAttribution = '© OpenStreetMap contributors © CARTO';
var DarkMatterUrl = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png'; // For dark theme map
var PositronUrl = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'; // For light theme map
var tiles = L.tileLayer(DarkMatterUrl, { MapAttribution }).addTo(mymap);
// Array of marker coordinates
var markers = [
{
coords:[4.21, 101.97],
country:'Malaysia',
label:'Malaysia',
},
{
coords:[20.594, 78.962],
country:'India',
label:'India',
},
{
coords:[35.861, 104.195],
country:'China',
label:'China',
},
{
coords:[23.421, 53.8478],
country:'UAE',
label:'UAE',
},
{
coords:[23.6978, 120.9605],
country:'Taiwan',
label:'Taiwan',
},
{
coords:[0.7892, 113.9213],
country:'Indonesia',
label:'Indonesia',
},
];
// Edit marker icons
var myIcon = L.icon({
iconUrl: 'yellowcircle.png',
iconSize: [40, 40], // size of the icon
// iconAnchor: [],
// popupAnchor: [],
});
// Loop through markers
for(var i = 0; i<markers.length; i++){
addMarker(markers[i]);
}
// To add the marker coordinates
function addMarker(props){
var marker = L.marker(props.coords, {icon: myIcon}).bindTooltip(props.country).addTo(mymap);
marker.on('mouseover', function(e){
marker.openPopup();
});
marker.on('mouseout', function(e){
marker.closePopup();
});
}
setOpacity() is from Dom Util
https://leafletjs.com/reference-1.6.0.html#domutil-setopacity
var mymap = L.map('map', {
center: [20.594, 78.962],
zoom: 4,
zoomSnap: 0.25,
zoomDelta: 0.25,
minZoom: 3.25,
maxZoom: 6,
zoomControl: true
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(mymap);
mymap.zoomControl.setPosition('topright');
L.DomUtil.setOpacity(mymap.zoomControl.getContainer(), 0.5);
#map {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"></script>
<div id="map"></div>
<!doctype html>
<html ng-app="App">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"></script>
<style>
#map {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%
}
</style>
</head>
<body>
<div ng-controller="Ctrl">
<div id="map"></div>
</div>
<script>
console.log(L.map)
var mymap = L.map('map', {
center: [23.022505, 72.571365],
zoom: 4,
zoomSnap: 0.25,
zoomDelta: 0.25,
minZoom: 3.25,
maxZoom: 6,
zoomControl: true
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(mymap);
mymap.zoomControl.setPosition('topright');
L.DomUtil.setOpacity(mymap.zoomControl.getContainer(), 0.5);
</script>
</body>
</html>
You have to add titleLayer into the L-map.
can you please refer my code.
You can use the plunker link for check my code:
Plunker Link:http://embed.plnkr.co/daSnET/
copy above code and paste into HTML file you can view a map and you can change opacity and check.
Related
I am trying out geofencing with leaflet and I have a marker that can be moved and a circle on a map.
Here is the full code:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<head>
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-locatecontrol/v0.43.0/css/font-awesome.min.css' rel='stylesheet' />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.5.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.5.1/dist/leaflet.js"></script>
</head>
<body>
<div id="mapid" style="height: 600px"></div>
<script>
var mymap = L.map('mapid', {
center: [50.897819, -1.150189],
zoom: 16
});
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoic3RldmVuc2F0Y2giLCJhIjoiY2p5eDR6MWgzMHRvbjNocnJkN2d2MjRwaSJ9.wd0OtBUQQfUtNxdduQA3lg', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(mymap);
var marker = new L.marker([50.898422, -1.148444],{
draggable: true,
autoPan: true
}).addTo(mymap);
var circle = L.circle([50.895763, -1.150556], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 200
}).addTo(mymap);
</script>
</body>
</body>
</html>
I need to detect when the marker going into and out of the circle.
How can I do this?
You can listen to the drag event to act when the marker is dragged
and you can then determine if the marker is inside your circle, for example by calculating the distance to the center.
Something like
marker.on('drag', function(e) {
// distance between the current position of the marker and the center of the circle
var d = mymap.distance(e.latlng, circle.getLatLng());
// the marker is inside the circle when the distance is inferior to the radius
var isInside = d < circle.getRadius();
// let's manifest this by toggling the color
circle.setStyle({
fillColor: isInside ? 'green' : '#f03'
})
});
And a demo
var mymap = L.map('mapid', {
center: [50.895763, -1.150556],
zoom: 16
});
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoic3RldmVuc2F0Y2giLCJhIjoiY2p5eDR6MWgzMHRvbjNocnJkN2d2MjRwaSJ9.wd0OtBUQQfUtNxdduQA3lg', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(mymap);
var marker = new L.marker([50.896422, -1.148444],{
draggable: true,
autoPan: true
}).addTo(mymap);
var circle = L.circle([50.895763, -1.150556], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 100
}).addTo(mymap);
marker.on('drag', function(e) {
var d = mymap.distance(e.latlng, circle.getLatLng());
var isInside = d < circle.getRadius();
circle.setStyle({
fillColor: isInside ? 'green' : '#f03'
})
});
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-locatecontrol/v0.43.0/css/font-awesome.min.css' rel='stylesheet' />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.5.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.5.1/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#5/turf.min.js"></script>
<div id="mapid" style="height: 180px"></div>
An alternative is to check if the circle is rendered at the pixel where the marker has been dragged to; this can be done by leveraging the Leaflet.CheapLayerAt plugin, e.g.:
<script src="https://unpkg.com/leaflet#1.5.1/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet.cheaplayerat#0.1.2/Leaflet.CheapLayerAt.js"></script>
and
marker.on('dragend', function(ev) {
// Hide the marker momentarily, so CheapLayerAt doesn't return it
marker.getElement().style.display = 'none';
if (map.getLayerAtLatLng(marker.getLatLng()) === circle) {
// The marker was dragged inside
} else {
// The marker was dragged outside
}
// Display the marker icon again
marker.getElement().style.display = 'inherit';
});
There are drawbacks with this approach - it's difficult to use id during a drag, because hiding the marker then displaying it again inside a drag operation might fire more DOM events and mess up things. If the marker looks like the default one, one could calculate instead the layer under the pixel just below the marker's tip, e.g.:
marker.on('drag', function(ev) {
var pxPos = map.latLngToContainerPoint(marker.getLatLng());
pxPos.y += 1;
if (map.getLayerAt(pxPos) === circle) {
// The marker was dragged inside
} else {
// The marker was dragged outside
}
});
Keep in mind that this approach will tell you when the marker has been dragged on the circle's border. If the stroke weight of the circle is too wide, you will get results when the marker is just over the border, even though the distance from the marker to the circle's center is larger than the circle radius.
So, even though this answers your question ("When is the marker dragged over the circle?"), I think you are asking the wrong question. For geofencing, you want to know if a point is within a given distance to another known point, so I would go with #nikoshr's answer.
I try to limit moving map out of focus but the map is fixed to centre and can't be moved.
var mapSW = [1000, 0],
mapNE = [1000, 0];
var map = L.map('map', {
crs: L.CRS.Simple,
zoomControl: true,
zoom: 1,
minZoom: 0,
maxZoom: 4
});
var bounds = [[-250,-500], [800,800]];
var image = L.imageOverlay('uqm_map_full.png', bounds).addTo(map);
map.fitBounds(bounds);
map.setMaxBounds(new L.LatLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom()),
));
If I enable setmaxBounds() map's background image fix to centre and can be moved elastically. Map move, until it is dragged, after drag end map back to its centre.
I tried to follow few examples but still no success.
Do you see where I make mistake?
Your mapSW and mapNE coordinates are identical, so the LatLngBounds that you can build out of them is of null area.
Furthermore, I am not sure why you carefully build bounds for your Image Overlay (image) and to have the map fit those bounds, then using complicated unproject with different coordinates to specify to setMaxBounds?
Live example using the same bounds for setMaxBounds, enabling navigation to the same bounds as the Image Overlay:
var map = L.map('map', {
crs: L.CRS.Simple,
zoomControl: true,
zoom: 1,
minZoom: 0,
maxZoom: 4
});
var bounds = [
[-250, -500],
[800, 800]
];
var image = L.imageOverlay('https://a.tile.openstreetmap.org/0/0/0.png', bounds, {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.fitBounds(bounds);
/*map.setMaxBounds(new L.LatLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom()),
));*/
map.setMaxBounds(bounds);
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet-src.js"></script>
<div id="map" style="height: 200px"></div>
If you wish to restrict user navigation to a different area than your image's bounds, you can easily do so by building similar bounds, without having to resort to unproject at all:
var map = L.map('map', {
crs: L.CRS.Simple,
zoomControl: true,
zoom: 1,
minZoom: 0,
maxZoom: 4
});
var bounds = [
[-250, -500],
[800, 800]
];
var image = L.imageOverlay('https://a.tile.openstreetmap.org/0/0/0.png', bounds, {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.fitBounds(bounds);
/*map.setMaxBounds(new L.LatLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom()),
));*/
map.setMaxBounds([
[-300, -600],
[900, 900]
]);
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet-src.js"></script>
<div id="map" style="height: 200px"></div>
I want google map like this Multiple Polyline, can Multiple select.
Multiple Polyline
var geocoder;
var map;
var polyline;
positions = [new google.maps.LatLng(37.441883,-122.143019),
new google.maps.LatLng(37.45296,-122.181725)];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
$("#chkRouteLines").click(function () {
if (!polyline || !polyline.setMap) {
polyline = new google.maps.Polyline({
path: positions,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
visible: true
});
}
if ($(this).is(':checked')) {
polyline.setMap(map);
} else {
polyline.setMap(null);
}
})
}
google.maps.event.addDomListener(window, "load", initialize);
html, body, #map_canvas {
height: 90%;
width: 100%;
margin: 0px;
padding: 0px
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
<input id="chkRouteLines" value="click" type="checkbox" />
you can google developers documents.For example this link:
https://developers.google.com/maps/documentation/javascript/examples/polyline-complex
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Polylines</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// This example creates an interactive map which constructs a polyline based on
// user clicks. Note that the polyline only appears once its path property
// contains two LatLng coordinates.
var poly;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.879, lng: -87.624} // Center the map on Chicago, USA.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// Add a listener for the click event
map.addListener('click', addLatLng);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
I am trying to display a highlighted circle when the user double clicks on a certain part of an image. For example, if the image is a map of a city, and they double click on coord: (X, Y), I want the highlighted circle's center to be at (X, Y) and the radius would vary on the item that they clicked on.
Here is what I have so far:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function showMap(){
var mapOptions = {
zoom: 19,
center: new google.maps.LatLng(x, y),//let z, y be some coord
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDoubleClickZoom: true,
disableDefaultUI: true,
zoomControl: false,
draggable: false,
scrollwheel: false
}
map = new google.maps.Map(document.getElementById("myMap"),
mapOptions);
google.maps.event.addListener(map, 'dblclick', doubleClicked);
}
function doubleClicked(e){//highlight the area with a circle
//alert("lat: " + e.latLng.lat() + "\nlong: " + e.latLng.lng());
}
</script>
HTML
<div id="myMap" ></div>
CSS
#myMap {
margin-left: auto;
margin-right: auto;
width: 1200px;
height: 800px
}
Solution with help from #Aamir Sarwar:
var circle = new google.maps.Circle({
strokeColor: '#FFFFFF',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: {lat: X, lng: Y}
radius: 10
});
check below example copy from this link...hope it may help you https://developers.google.com/maps/documentation/javascript/examples/rectangle-simple?hl=en
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Rectangles</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
<script>
// This example adds a red rectangle to a map.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 33.678, lng: -116.243},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: {
north: 33.685,
south: 33.671,
east: -116.234,
west: -116.251
}
});
}
</script>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap"></script>
</body>
</html>
Here's the general outline:
myMap should be position:relative
Add mouse events on myMap to track X,Y of the mouse position
in doubleClicked method, create div that would be displayed as circle. Also it should be position:absolute
add that element to the myMap and change its CSS: left to mouse X position and top to mouse Y position
I want to map a route between two points on Google Maps with a polyline and overlay this with another "current distance travelled" polyline. Basically, if the distance between the two points is 100KM and the person has travelled 25KM I want to overlay a second polyline 25% of the route. I am finding it difficult to find even a formula to calculate what the coordinates of the point 25% along this route would be.
Is there any Google map functionality to do something like this, or a technique for calculating a point along a route, x% of the way.
Thanks in advance.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Polylines</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&signed_in=true"></script>
<script type="text/javascript" src="v3_epoly.js"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(0, -180),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(-27.46758, 153.027892)
];
var lineSymbol = {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 4
};
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#999999',
strokeOpacity: 0,
icons: [{
icon: lineSymbol,
offset: '0',
repeat: '20px'
}],
});
flightPath.setMap(map);
//current location 2000 miles on route
var mar = flightPath.GetPointAtDistance(2000000);
var myLatlng = new google.maps.LatLng(mar.k, mar.D);
console.log(mar);
var marker = new google.maps.Marker({
position: mar,
map: map,
title: 'Current Location'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="height:100%; width:100%;"></div>
</body>
</html>