how to pass multiple location in leaflet map - javascript

i need to display multi marker in leaflet map using vuejs. and i also need to chcnge marker image i have given code below only for single maker.
mounted () {
// L.Icon.Default.imagePath = 'assets/vendor/leaflet' TODO: make it work with webpack
Leaflet.Icon.Default.imagePath = 'https://unpkg.com/leaflet#1.0.3/dist/images'
let map = Leaflet.map(this.$refs['mapElement']).setView([51.505, -0.09], 13)
Leaflet.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
}).addTo(map)
Leaflet.marker([51.5, -0.09]).addTo(map)
.openPopup()
},
below is my api output data
[[51.4, -0.03],[53.5, -0.39],[52.5, -0.39]]

I believe you can use the solution here with your API output.
var res = [[51.4, -0.03],[53.5, -0.39],[52.5, -0.39]];
for (var i = 0; i < res.length; i++) {
marker = new L.marker(res[i])
.addTo(map);
}
Hope that answers your question.

Related

How to add MapQuest RouteLayer to leaflet layer

i want to implement in my leaflet app, feature that allows to find route between two selected points.To find route i want to use this library: mapquest
I have extended standard leaflet map class like this:
export class Map {
constructor(elementId, centerView, zoom ) {
this.layers = [];
this.map = this.init(elementId,centerView,zoom);
this.icons = {};
}
init(elementId, centerView, zoom) {
//console.log('Map::init('+elementId+', ['+centerView+'], '+zoom+')');
delete L.Icon.Default.prototype._getIconUrl;
const markerIcon = require('leaflet/dist/images/marker-icon.png');
const markerIcon2x = require('leaflet/dist/images/marker-icon-2x.png');
const markerShadow = require('leaflet/dist/images/marker-shadow.png');
L.Icon.Default.mergeOptions({
iconRetinaUrl: markerIcon2x.default,
iconUrl: markerIcon.default,
shadowUrl: markerShadow.default,
});
var map = L.map(elementId, {
center: [centerView[0], centerView[1]],
zoom: zoom
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
return map;
}
}
And i wrote few functions that helps me to work with map(add point, markers etc).
This is how i'm initializing extended map object:
let centerView = [35.791188, -78.636755];
let zoom = 9;
var map = new Map('map', centerView, zoom);
And i found code how to generate route mapquest-routing.I'am taking coords by clicking on map which works fine. My function to generate route looks like this:
function runDirection(start, end)
{
var dir = MQ.routing.directions();
dir.route({
locations: [
start,
end
]
});
map.map.addLayer(MQ.routing.routeLayer({
directions: dir,
fitBounds: true
}));
}
But i'm getting error:
Uncaught Error: The provided object is not a Layer.
Which means MQ.routing.routeLayer(),doesnt return me leyer object.
So the question is, how can i add route to standard leaflet map?
You're using a deprecated library. On the https://developer.mapquest.com/documentation/leaflet-plugins/geocoding/ webpage there's a deprecation warning in big red letters, I quote:
We recommend using MapQuest.js instead.
The documentation in the webpage for that mapquest plugin for Leaflet lists compatibility for Leaflet 0.7.7 (which was published back on 2013). Leaflet uses semantic versioning, which means stuff that worked with 0.x has no guarantee of working with 1.x. It's safe to assume that the Leaflet plugin in question only works with Leaflet 0.7.x and older, and does not work with Leaflet 1.x.

How to remove old map markers and update new in Google Maps [duplicate]

This question already has answers here:
Google Map API - Removing Markers
(5 answers)
Closed 3 years ago.
I'm creating an application which gets the real-time location and renders to Google Map. After a specific time interval, I have to remove old markers and need to render the udpated markers.
Below is my code
function initMap(rtl_data) {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var latlng = new google.maps.LatLng(24.238162, 45.156379);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var marker = []
var map = new google.maps.Map(document.getElementById("map"),myOptions);
directionsDisplay.setMap(map);
makeMarkers(rtl_data)
function makeMarkers(rtl_data){
// Drivers Location Markers
deleteMarkers()
features = []
marker = []
drivers_latlng = rtl_data.drivers_latest_location
drivers_latlng.forEach(function(e){
features.push({
position: new google.maps.LatLng(e.lat, e.lng),
type: e.order_id,
title: e.driver_id,
description: e.order_id ? "Ongoing order: "+e.order_id : "No order assigned."
})
})
image = "/files/truck.png"
infoWindow = new google.maps.InfoWindow();
for (i = 0; i < features.length; i++) {
marker = new google.maps.Marker({
position: features[i].position,
map: map,
title: features[i].title,
type: features[i].type,
icon: image,
description: features[i].description
});
//Attach click event to the marker.
(function (marker) {
google.maps.event.addListener(marker, "click", function (e) {
//Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + marker.description + "</div>");
infoWindow.open(map, marker);
});
})(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < marker.length; i++) {
marker[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
console.log('clearMarkers')
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
console.log('deleteMarkers')
clearMarkers();
marker = [];
}
}
// Fetch Realtime using time interval
setInterval(function() {
frappe.call({ // Simple AJAX Call which returns locations and location realated data.
method: "get_drivers_locations",
async: false,
callback: function(r){
rtl_data = r.message
}
})
makeMarkers(rtl_data)
}, 5000);
I already used Method's which is used in the documentaion by Google Map.
Using ClearMarkers the old markers get cleared. But in my case it is not working.
When I run above code it displaying me both old and upadted markers.
See below screenshot which is repetating markers with updated locations.
You initialize marker as an array:
var marker = []
But later assign a Marker instance:
marker = new google.maps.Marker({...})
I didn't run your example, but I expect, that marker variable will contain not an array of markers, but the last created marker.
Try to do next:
rename marker variable to markers
implement addMarker function. This function should push a new marker to markers array
After reading below thread:
Google Map API - Removing Markers
I found the solution.
I created one array.
gmarkers = []
and pushed all my new markers in it.
gmarkers.push(marker)
To delete the markers I used the following function.
function setMapOnAll(map) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(map);
}
}
Your closure bracket for the init function is wrong. If you look at the original documentation the init function is closed before the addmarker function. In your example it is closed just before the setInterval. So your setInterval probably can't even access the makeMarker function because this one is inside another function.

Angular only update objects if it has been changed since last poll

Im polling data from my web api to populate a map with markers. The markers has positions, and Im saving the markers in the following way
allMarkers: Map<Number, Leaflet.Marker> = new Map();
At the moment I am refreshing the markers each time I poll my data, which is every 10 seconds. What I would like to do is to only refresh the markers who's position has actually changed. Is there any effecient way I can do that? I tried to use a "oldAllMarkers" and "newAllMarkers" but it didn't do much.
See my code below and please let me know if there is anything I should add to make things for clear.
// ngOnInit with a bunch of things. Here is where I set up my map and poll
// my data with the use of my subscribeToData function.
ngOnInit() {
// Init map
this.map = new Leaflet.Map('mapid', {}).setView([this.lng, this.lat], 10);
this.tiles = new Leaflet.TileLayer(
,
{
attribution: `Map data © OpenStreetMap contributors,
CC-BY-SA,
Imagery © Mapbox`,
maxZoom: 18,
minZoom: 1,
id: 'mapbox.streets',
accessToken:
}
).addTo(this.map);
// init vehicles details
this.store.select(fromStore.getAllVehicleDetails).subscribe(data => {
this.vehicleDetails = data;
this.setMarkers(this.selected);
// set the selected vehicle
this.vehicleDetail = this.getVehicleDetail(this.selected);
// set/refresh the markers
this.setMarkers(this.selected);
});
this.store.dispatch(new fromStore.LoadVehicleDetails());
this.subscribeToData();
}
setMarkers(id: number) {
for (let i = 0; i < this.vehicleDetails.length; i++) {
// Refresh markers
if (this.allMarkers.get(this.vehicleDetails[i].id)) {
const tempMarker = this.allMarkers.get(this.vehicleDetails[i].id);
this.allMarkers.delete(this.vehicleDetails[i].id);
if (tempMarker) {
this.map.removeLayer(tempMarker);
console.log('refresh map marker');
}
}
// Creating the markers
this.getIcon(this.vehicleDetails[i], status);
// set markers to our hashpmap.
if (this.markers) {
this.allMarkers.set(this.markers.options.vehicleId, this.markers);
}
}
// hide progress bar
this.loading = false;
}
}

I'm using Google Maps in React and my markers don't always load?

So as the title says, I'm using React and trying to implement Google Maps with list of places fetched from Foursquare and display their markers. I'm not using any packages such as react-google-maps etc, just vanilla JS. The map loads just fine, the places are fetched BUT the markers show every now and then. When they do load, they point to correct location but they load rarely. I'm not sure what's wrong with my createMarkers function here:
// Initialize map
initMap = () => {
let map = new window.google.maps.Map(document.getElementById("map"), {
zoom: 14,
center: {lat: 45.5616873, lng: 18.6770196 }
});
this.createMarkers(map);
}
// The following function uses the places array to create an array of markers on initialize.
createMarkers = (map) => {
for (let i = 0; i < this.state.places.length; i++) {
// Get the position from the location array
let position = this.state.places[i].location;
let name = this.state.places[i].name;
let venueID = this.state.places[i].venueID;
// Create a marker per location, and put into markers array.
let marker = new window.google.maps.Marker({
position: position,
name: name,
animation: window.google.maps.Animation.DROP,
icon: this.state.defaultIcon,
venueID: venueID,
map: map
});
// Set state to save the marker to our array of markers.
this.setState((state) => ({
markers: [...state.markers, marker]
}))
}
}
// Create default marker icon
makeMarkerIcon(markerColor) {
const markerImage = new window.google.maps.Icon(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|'+ markerColor +
'|40|_|%E2%80%A2',
new window.google.maps.Size(21, 34),
new window.google.maps.Point(0, 0),
new window.google.maps.Point(10, 34),
new window.google.maps.Size(21,34)
);
return markerImage;
};
Any help would be much appreciated, as I'm still new to React and prone to beginner's mistakes.

Leaflet: update map

Here is my function that I use to draw a Leaflet map in my website:
function drawTweetMap(points) {
if (tweetMap != null)
tweetMap.remove();
var london = [51.505, -0.09];
tweetMap = L.map('tweetMap').setView(london, 5);
var cloudmadeUrl = 'http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.jpg';
var subDomains = ['otile1','otile2','otile3','otile4'];
var cloudmadeAttrib = 'Data, imagery and map information provided by MapQuest, OpenStreetMap and contributors, CC-BY-SA';
L.tileLayer(cloudmadeUrl,
{attribution: cloudmadeAttrib,
maxZoom: 18,
subdomains: subDomains})
.addTo(tweetMap);
var markers = L.markerClusterGroup();
var points_rand = L.geoJson(points, {onEachFeature: onEachFeature});
markers.addLayer(points_rand);
tweetMap.addLayer(markers);
tweetMap.fitBounds(markers.getBounds());
}
This function is called periodically:
mapWatch = setInterval(function() {
retrieveCurrentTweetPositions()},
numMinutes*60*1000);
in this function:
function retrieveCurrentTweetPositions() {
var points = retrieveCurrentPositions();
var mapInput = translatePointsInMapFormat(points);
drawTweetMap(mapInput);
}
Unfortunately, if the map is drawn in this way, the result is the following:
In other questions I found that it is possible to invalidate the size of the map to fix this problem, so it was suggested to call on startup this function:
function updateTweetMapPosition() {
setTimeout(function(){
tweetMap.invalidateSize(true);}
,500)
}
I did so, and this solves the problem during the first map drawing. However, when I try to redraw the map for a second time, the result is as follows:
Has anyone experienced this problem? How can I redraw the map with a full loading of its content?
Thanks.
EDIT
Here is the jsFiddle: http://jsfiddle.net/qzpwvqzk/
I solved the problem as follows
setTimeout(function(){map.invalidateSize(true);},500);
Use https://leafletjs.com/reference-1.7.1.html#map-invalidatesize
tweetMap.invalidateSize()
Take a look at the redraw() method.

Categories

Resources