Hello Everyone need Help setting Multiple markers to google map component in Angular 4. I can get a single Marker to show up with this code.
ngOnInit() {
const myLatlng = new google.maps.LatLng(40.748817, -73.985428);
const mapOptions = {
zoom: 13,
center: myLatlng,
scrollwheel: false
};
const map = new google.maps.Map(document.getElementById('map'), mapOptions);
const Marker = new google.maps.Marker({
position: myLatlng,
title: 'Hello World!'
});
// To add the marker to the map, call setMap();
Marker.setMap(map);
}
How can I modify this to show multiple locations. I have locations in from JSON like below.
{
"locations": [
{
"_id": "59eb784fa8e0be0004fb466e",
"updatedAt": "2017-10-21T16:39:43.338Z",
"createdAt": "2017-10-21T16:39:43.338Z",
"latitude": "0.2346285",
"longitude": "32.4352628",
"locationName": "Prime warehouse A",
"locationInfo": "Kampala Warehouse #001",
"__v": 0
},
{
"_id": "1568eb54560be000456466e",
"updatedAt": "2018-10-21T16:39:43.448Z",
"createdAt": "2016-09-11T16:39:43.338Z",
"latitude": "4.3346285",
"longitude": "32.4352628",
"locationName": "Prime warehouse A",
"locationInfo": "Kampala Warehouse #001",
"__v": 0
}
]
}
As long as you can access your locations array, then you can loop through it and from there create a marker each.
Here's a sample if you put everything in your ngOnInit function:
ngOnInit() {
let map;
const locations; // if you have your locations hard-coded, else just make sure it's accessible
const myLatlng = new google.maps.LatLng(40.748817, -73.985428);
const mapOptions = {
zoom: 13,
center: myLatlng,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// loop through each object of your locations array
for (let location in locations) {
// The marker's position property needs an object like { lat: 0, lng: 0 };
// Number(location.latitude) is there to convert the string to a number, but if it's a number already, there's no need to cast it further.
let latLng = {lat: Number(location.latitude), lng: Number(location.longitude)};
// Set the position and title
let marker = new google.maps.Marker({
position: latLng,
title: location.locationName
})
// place marker in map
marker.setMap(map)
}
}
You can learn more about importing data into a Map with Google's official documentation
Hope that helps!
Related
Mapbox is being used across the site, however, isn't loading on two specific pages?
There are three maps, all of which display fine on this page. And here is a working example of the page I am looking to replicate elsewhere, only with a different map. However, on this page the map doesn't load?
This is the javascript I'm using, each map has a different var, stroud, gloucester and brimscombe.
mapboxgl.accessToken = 'validtokenhere';
// STROUD
var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"message": "Visit our Stroud clinic",
"iconSize": [30, 40]
},
"geometry": {
"type": "Point",
"coordinates": [
-2.248550,
51.741290
]
}
},
]
};
var stroud = new mapboxgl.Map({
container: 'stroud',
style: 'mapbox://styles/mapbox/light-v9',
center: [-2.248550,51.741290],
zoom: 13
});
// disable map zoom when using scroll
stroud.scrollZoom.disable();
// add markers to map
geojson.features.forEach(function(marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(/assets/img/marker.png)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.addEventListener('click', function() {
window.alert(marker.properties.message);
});
// add marker to map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(stroud);
});
// GLOUCESTER
var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"message": "Visit our Gloucester clinic",
"iconSize": [30, 40]
},
"geometry": {
"type": "Point",
"coordinates": [
-2.248140,
51.870560
]
}
},
]
};
var gloucester = new mapboxgl.Map({
container: 'gloucester',
style: 'mapbox://styles/mapbox/light-v9',
center: [-2.248140,51.870560],
zoom: 13
});
// disable map zoom when using scroll
gloucester.scrollZoom.disable();
// add markers to map
geojson.features.forEach(function(marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(/assets/img/marker.png)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.addEventListener('click', function() {
window.alert(marker.properties.message);
});
// add marker to map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(gloucester);
});
// BRIMSCOMBE
var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"message": "Visit our Brimscombe clinic",
"iconSize": [30, 40]
},
"geometry": {
"type": "Point",
"coordinates": [
-2.063020,
51.892550
]
}
},
]
};
var brimscombe = new mapboxgl.Map({
container: 'brimscombe',
style: 'mapbox://styles/mapbox/light-v9',
center: [-2.063020,51.892550],
zoom: 13
});
// disable map zoom when using scroll
brimscombe.scrollZoom.disable();
// add markers to map
geojson.features.forEach(function(marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(/assets/img/marker.png)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.addEventListener('click', function() {
window.alert(marker.properties.message);
});
// add marker to map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(brimscombe);
});
and then each container is
<section class="location-map-image">
<div id="stroud" class="map" style="width: 100%; height: 263px;"></div>
</section>
obviously the div id changes to match the location I wish to display.
I am expecting to see Gloucester and Brimscombe load like Stroud does?
Console log is showing
Error: Container 'stroud' not found. map.js:337:22
r map.js:337
<anonymous> app-min.js:12508
So it appears that the script gets stuck when it cannot find the div id stroud. What should I be doing when I only want to show gloucester or brimscombe?
TL:DR; There is no HTML element for the map to render in
The error you're seeing is because there is no div tag on this page with the id of stroud or brimscombe, so Mapbox doesn't know where to render the map.
If you go to the stroud clinic page, you'll notice that you get errors for briscombe and gloucester, because neither of those divs exist.
EDIT:
If you want to not see the errors, there are a few different ways you could do it, but I'd do it something like this:
// Checking if the element stroud exists
if (!!document.getElementById('stroud')) {
// If it does, run the stroud code
}
You can repeat that pattern for your other two as well. No need to provide an else unless you want to.
I have used 'Leaflet.markercluster' plugin with leaflet library to display the cluster & spiderfy in my map.
But when applying the latitude & longitude coordinates in marker, if the coordinates are nearby / very close, then both coordinates are displayed in a single spiderfy view.
Actually, I wanted to display those coordinates as a separate marker.
In Example, You can see in 'markers' array, I have used the first two object with identical coordinates and the third one differs from the first two. But all three marker display in single spiderfy. Actually, I wanted first two as spiderfy and third one as a separate marker.
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.4.1/MarkerCluster.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.4.1/MarkerCluster.Default.css" />
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet.js"></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.4.1/leaflet.markercluster.js'></script>
</head>
<body>
<h1>Leaflet Cluster Example</h1>
<p>Here's an interactive map indicating where airports and train stations are located around the world. The data comes from OpenFlights.org.
<div id="map" style="width: 800px; height: 500px; border: 1px solid #AAA;"></div>
<script type="text/javascript">
var markers = [{
"name": "Goroka",
"city": "Goroka, Papua New Guinea",
"iata_faa": "GKA",
"icao": "AYGA",
"lat": 38.98856,
"lng": -77.32219,
"alt": 5282,
"tz": "Pacific/Port_Moresby"
}, {
"name": "Madang",
"city": "Madang, Papua New Guinea",
"iata_faa": "MAG",
"icao": "AYMD",
"lat": 38.98856,
"lng": -77.32219,
"alt": 20,
"tz": "Pacific/Port_Moresby"
}, {
"name": "Mount Hagen",
"city": "Mount Hagen, Papua New Guinea",
"iata_faa": "HGU",
"icao": "AYMH",
"lat": 38.98852,
"lng": -77.32183,
"alt": 5388,
"tz": "Pacific/Port_Moresby"
}];
var map = L.map('map', {
center: [10.0, 5.0],
minZoom: 2,
maxZoom: 18,
zoom: 2
});
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
subdomains: ['a', 'b', 'c']
}).addTo(map);
var myIcon = L.icon({
iconUrl: 'http://cdn.leafletjs.com/leaflet-0.7.3/images/marker-icon.png',
iconSize: [29, 24],
iconAnchor: [9, 21],
popupAnchor: [0, -14]
});
var markerClusters = L.markerClusterGroup();
for (var i = 0; i < markers.length; ++i) {
var popup = markers[i].name +
'<br/>' + markers[i].city +
'<br/><b>IATA/FAA:</b> ' + markers[i].iata_faa +
'<br/><b>ICAO:</b> ' + markers[i].icao +
'<br/><b>Altitude:</b> ' + Math.round(markers[i].alt * 0.3048) + ' m' +
'<br/><b>Timezone:</b> ' + markers[i].tz;
var m = L.marker([markers[i].lat, markers[i].lng], {
draggable: true,
icon: myIcon
})
.bindPopup(popup);
markerClusters.addLayer(m);
}
markerClusters.on("clusterclick", function(c) {
var cluster = c.layer,
bottomCluster = cluster;
while (bottomCluster._childClusters.length === 1) {
bottomCluster = bottomCluster._childClusters[0];
}
if (bottomCluster._zoom === markerClusters._maxZoom &&
bottomCluster._childCount === cluster._childCount) {
c.layer.zoomToBounds();
}
});
map.addLayer(markerClusters);
</script>
</body>
Please how to resolve this?
Leaflet.markercluster by default clusters Markers which are closer than 80 pixels (see option maxClusterRadius).
Therefore if at maximum map zoom, your 3 Markers are still within 80 pixels from each other, the plugin will put them in the same cluster, and spiderfy all 3 of them together.
Now if you do not want those Markers clustering at maximum zoom unless they are exactly at the same position, you would be interested in Leaflet.markercluster #339:
[...] it seems to me that in fact you want "no clustering" at zoom level 15 and higher, EXCEPT for markers which are at the VERY SAME position (lat/lng).
You could approach this functionality by using a maxClusterRadius function that returns normal radius (default 80 pixels) for zoom levels 0 to 14, and 1 pixel for level 15 and beyond:
var mcg = L.markerClusterGroup({
maxClusterRadius: function (zoom) {
return (zoom <= 14) ? 80 : 1; // radius in pixels
}
});
With this, for zoom level 15 and higher, the plugin will still cluster markers that are within 1 pixel from each other. If I recall correctly, using 0 pixel does not work unfortunately. But 1 pixel distance is already very small, as if the markers were at the very same position.
Example:
var markers = [{
"name": "Goroka",
"city": "Goroka, Papua New Guinea",
"iata_faa": "GKA",
"icao": "AYGA",
"lat": 38.98856,
"lng": -77.32219,
"alt": 5282,
"tz": "Pacific/Port_Moresby"
}, {
"name": "Madang",
"city": "Madang, Papua New Guinea",
"iata_faa": "MAG",
"icao": "AYMD",
"lat": 38.98856,
"lng": -77.32219,
"alt": 20,
"tz": "Pacific/Port_Moresby"
}, {
"name": "Mount Hagen",
"city": "Mount Hagen, Papua New Guinea",
"iata_faa": "HGU",
"icao": "AYMH",
"lat": 38.98852,
"lng": -77.32183,
"alt": 5388,
"tz": "Pacific/Port_Moresby"
}];
var map = L.map('map', {
center: [38, -77],
minZoom: 2,
maxZoom: 18,
zoom: 2
});
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap'
}).addTo(map);
var markerClusters = L.markerClusterGroup({
// From https://github.com/Leaflet/Leaflet.markercluster/issues/339
maxClusterRadius: function(zoom) {
return (zoom <= 14) ? 80 : 1; // radius in pixels
}
});
for (var i = 0; i < markers.length; ++i) {
var popup = markers[i].name +
'<br/>' + markers[i].city +
'<br/><b>IATA/FAA:</b> ' + markers[i].iata_faa +
'<br/><b>ICAO:</b> ' + markers[i].icao +
'<br/><b>Altitude:</b> ' + Math.round(markers[i].alt * 0.3048) + ' m' +
'<br/><b>Timezone:</b> ' + markers[i].tz;
var m = L.marker([markers[i].lat, markers[i].lng])
.bindPopup(popup);
markerClusters.addLayer(m);
}
map.addLayer(markerClusters);
html,
body,
#map {
height: 100%;
margin: 0;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.4.1/MarkerCluster.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.4.1/MarkerCluster.Default.css" />
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet.js"></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.4.1/leaflet.markercluster.js'></script>
<div id="map"></div>
Currently I am passing Json data as
coords: [
{lat: 27.17841526682381, lng: 73.29395468749999},
{lat: 24.88842099751237, lng: 73.64551718749999}
]
Instead of this, I need to send Json data as
coords: [
{27.17841526682381, 73.29395468749999},
{24.88842099751237, 73.64551718749999}]
How can I able to achieve the same. How can I obtain these result.
All you need is a very simple map() operation
const coords = [
{lat: 27.17841526682381, lng: 73.29395468749999},
{lat: 24.88842099751237, lng: 73.64551718749999}
]
const res = coords.map(o => [o.lat, o.lng])
console.log(res)
The easiest way is to use Array#map() with Object.values() as a callback:
coords = coords.map(Object.values);
Note:
Note that your desired output format is incorrect because the inner objects aren't valid objects, they should be arrays.
Demo:
let coords = [
{lat: 27.17841526682381, lng: 73.29395468749999},
{lat: 24.88842099751237, lng: 73.64551718749999}
];
coords = coords.map(Object.values);
console.log(coords);
Try this.... use Object.values()
var coords= [
{lat: 27.17841526682381, lng: 73.29395468749999},
{lat: 24.88842099751237, lng: 73.64551718749999}
]
let items = [];
for (var prop in coords) {
var val= Object.values(coords[prop]);
items.push(val)
}
console.log(items)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Assuming that your output should be a nested array like:
[[27.17841526682381,73.29395468749999],
[24.88842099751237,73.64551718749999]]
You can use reduce on your array of objects to achieve this in the following way:
var coords = [
{lat: 27.17841526682381, lng: 73.29395468749999},
{lat: 24.88842099751237, lng: 73.64551718749999}
];
var formattedCoords = coords.reduce((dict, item) => [...dict, [item.lat, item.lng]], []);
console.log(formattedCoords);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
This is my code to create multiple waypoints.
I have an array with 'n' number of lattitude and longitude i want the route based on that lat,long.I don't want to use any hardcore data's in waypoints.
In waypoints array i want to use dynamic lattitude and longitude,how to use this?
var data = [
{
"title": 'Chennai',
"lat": '13.0827',
"lng": '80.2707',
"description": '',
"flag":'1'
}
,
{
"title": 'Ramapuram',
"lat": '13.0317',
"lng": '80.1817',
"description": ''
}
,
{
"title": 'Kanchipuram',
"lat": '12.8342',
"lng": '79.7036',
"description": '',
"flag":'1'
},
];
var map = L.map('map');
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var routeControl = L.Routing.control({
}).addTo(map);
routeControl.setWaypoints(data);
Here i have attached the image and this is my output,and also my expectation is i want to remove the center marker.i want to set the marker where i want.
Can anyone help me out?Now i have updated my code that i removed waypoints and i set the waypoints using setwaypoints function.Now i wantto remove the markers.
If I understand correctly, you want to draw a route along some waypoints and show markers only for start and end points. Also you want to prevent users from adding new waypoints. Create control like that:
L.Routing.control({
waypoints: yourWaypoints,
plan: L.Routing.plan(yourWaypoints, {
createMarker: function(i, wp, n) {
if (i == 0 || i == n - 1) {
return L.marker(wp.latlng, {
draggable: false // prevent users from changing waypoint position
});
} else {
return false;
}
}
},
addWaypoints: false // prevent users from adding new waypoints
});
I want to display a map (Google maps initially) in a website (e.g. the position of some runners in an event/race), alongisde some markers with the initials of each runner. That is, depending on the data I get in JSON format:
data = [
{
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
}
{
"lat": 44.473,
"lng": 3.144,
"full_name": "Mark Zein"
}
...
]
I would like to represent the current position of each runner in the map with a marker identified by its initials (Mark Zein --> M.Z.). For instance (forgive me for this representation):
-----
|M.Z| _______________________road
----- --|-- /
|P.C| _________v________|
--|-- /
___v__________/
I know I can create a google.maps.Marker with a custom icon, but I am finding hard to create these icons dinamically based on data I receive (and that might change over time).
Is there a way to dynamically create images/icons from data? Or can you think of another way of generating these icons?
I've been doing some research but so far I didn't find something, so any help will be much appreciated!
Edited:
I am currently mocking the way I get the data, but the idea is to get the data from a socket. So what I have in my code right now is:
var json_socket = {
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
};
And how I add the markers:
var live_user = {lat: json_socket["lat"], lng: json_socket["lng"]};
var marker = new google.maps.Marker({
position: live_user,
map: map,
icon: "icon.png"
});
You can iterate over the array of markers with simple loop
I used the label to display the initials
var data = [{
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
} {
"lat": 44.473,
"lng": 3.144,
"full_name": "Mark Zein"
}
...
];
for (var i = 0; i < data.length; i++) {
var item = data[i];
var latLng = new google.maps.LatLng(item.lat, item.lng);
var initials = item.full_name.match(/\b(\w)/g).join('');
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
label: initials,
icon: "icon.png"
});
}