Adding Multiple Markers on Vue JS Google Maps - javascript

I have Google Maps embedded on Vue JS code. But I want to show multiple markers using latitude and longitude on that map. Any idea on how to do that?
Here is my code.
Maps.vue
<template>
<card type="plain" title="Google Maps">
<div id="map" class="map">
</div>
</card>
</template>
<script>
export default {
mounted() {
let myLatlng = new window.google.maps.LatLng(40.748817, -73.985428);
let mapOptions = {
zoom: 13,
center: myLatlng,
scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page
styles: [{
"elementType": "geometry",
"stylers": [{
"color": "#1d2c4d"
}]
},
{
"elementType": "labels.text.fill",
"stylers": [{
"color": "#8ec3b9"
}]
},
{
"elementType": "labels.text.stroke",
"stylers": [{
"color": "#1a3646"
}]
},
{
"featureType": "water",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#4e6d70"
}]
}
]
};
let map = new window.google.maps.Map(
document.getElementById("map"),
mapOptions
);
let marker = new window.google.maps.Marker({
position: myLatlng,
title: "Hello World!"
});
marker.setMap(map);
}
};
</script>
How can I display multiple markers on this google map? Any advice or tips would be really helpful. Thanks.

You can use the gmap-vue plugin for VueJS to add multiple markers by clicking on the map.
First, initialize your Google Map, and make sure to add an array of markers: [] that will contain all the markers that you will be adding on the map:
<template>
<div>
<gmap-map
:center="center"
ref="mmm"
:zoom="12"
style="width: 100%; height: 400px"
#click="addMarker"
>
<gmap-marker
:key="index"
v-for="(m, index) in markers"
/>
</gmap-map>
</div>
</template>
export default {
name: "GoogleMap",
data() {
return {
center: { lat: 45.508, lng: -73.587 },
markers: [],
};
},
};
You can add markers by calling the #click="addMarker" event on <gmap-map>. Then, on the your methods you can add the addMarker(event) function where you should be able to get the click coordinates from the map. You can now
Here is what it looks like:
methods: {
addMarker(event) {
const marker = {
lat: event.latLng.lat(),
lng: event.latLng.lng(),
};
console.log(marker);
this.markers.push({ position: marker });
this.$refs.mmm.panTo(marker);
//this.center = marker;
},
},
Here is a working codesandbox for your reference, just put your API key on the main.js file: https://codesandbox.io/s/gifted-fast-b41ps

You can use- but you don't need any plug-in. It doesn't really save time in this use-case imho.
With the standard implementation it would look something like that:
this.yourPOIs.forEach(poi => {
var myLatLng = { lat: poi.latitude, lng: poi.longitude };
var marker = new google.maps.Marker({
position: myLatLng,
map: this.myMap,
title: poi.annotation
// you can also add data here with key names that are not in use like for example "uuid: 1" so you can access that data later on if you click on markers or iterate through them
});
marker.addListener('click', function() {
console.log(marker.uuid); // if you want to react on clicking on a marker
});
this.addedMarkers.push(marker);
});
myMap being the map object written in a local variable instead of writing it in a let-variable (you will probably need to access the map later on so you better safe them in the local data of the component or your vuex store).
That's also why i pushed the markers in an array of the component. By that you can later on do this to delete the markers again (for e.g. updating the map):
this.addedMarkers.forEach(marker => {
marker.setMap(null);
});

Related

Difficulty changing style of google map on button click

So I have a map using the google map api and I'm trying to change the water color on a button click.
I've been struggling with this one for a while now.
I initialised the map variable outside of the initMap function but that didn't seem to change anything.
var map;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 40.674,
lng: -73.945
},
zoom: 12,
styles: [
{
featureType: 'water',
elementType: 'geology',
stylers: [{color: '#17263c'}]
}
]
});
}
function showTest() {
var myStyle =[{
featureType: 'water',
elementType: 'geometry',
stylers: [
{ color: '#fc0101' }
]
}];
map.setOptions({styles: myStyle});
}
Even though you initialised a map variable outside your initMap function, the fact you then declare a map variable inside that function prefixed with var, makes it local to just that function.
Change that to:
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {

Drawing a circle around a point in vue2-google-maps

I am using Vue to build a site that takes in some data and displays a google map with markers and circles around the points with the markers.
So far I can create the map with markers perfectly fine, however I have no idea what the proper way to create a circle is with the Vue2-google-maps package, despite having combed through the Documentation for a long time.
Here is the code so far
<GmapMap
:center="center"
:zoom="10"
class="google-map">
<GmapMarker
:key="index"
v-for="(pin, index) in markers"
:position="pin.position"
:icon="pin.icon"
:clickable="true"
:draggable="true"
#click="center=pin.position">
</GmapMarker>
<GmapCircle
:key="index"
v-for="(pin, index) in markers"
:center="pin.position"
:radius="1000"
:visible="true"
:fillColor="red"
:fillOpacity:="1.0">
</GmapCircle>
</GmapMap>
Note that markers is a list of markers that is created somewhere else in the code.
If you take out the tags, the code works perfectly fine placing all the markers. I just need to know what the proper tag/object set is for creating a circle.
You are on the right track, GmapCircle component in vue2-google-maps library is intended for creating circles on the map. There are might be several reasons why circles are not getting displayed:
center property value is invalid, the supported format is {lat: <lat>, lng: <lng>} or google.maps.LatLng value
maybe you could not spot them due to relatively small size (given the provided 2 kilometer diameter, they could be easily missed)?
Regarding fillColor and fillOpacity properties, they need to be passed via options property, e.g. :options="{fillColor:'red',fillOpacity:1.0}"
Anyway the following example demonstrates how to create circles on map via vue2-google-maps
<GmapMap :center="center" :zoom="zoom" ref="map">
<GmapCircle
v-for="(pin, index) in markers"
:key="index"
:center="pin.position"
:radius="100000"
:visible="true"
:options="{fillColor:'red',fillOpacity:1.0}"
></GmapCircle>
</GmapMap>
export default {
data() {
return {
zoom: 5,
center: { lat: 59.339025, lng: 18.065818 },
markers: [
{ Id: 1, name: "Oslo", position: { lat: 59.923043, lng: 10.752839 } },
{ Id: 2, name: "Stockholm", position: { lat: 59.339025, lng: 18.065818 } },
{ Id: 3, name: "Copenhagen", position: { lat: 55.675507, lng: 12.574227 }},
{ Id: 4, name: "Berlin", position: { lat: 52.521248, lng: 13.399038 } },
{ Id: 5, name: "Paris", position: { lat: 48.856127, lng: 2.346525 } }
]
};
},
methods: {}
};
in my case, i had error that saw:" GmapCircle not define component", so i have used this code:
<gmap-circle
v-for="(infoWindow, index) in arrayMarkers"
:key="'circle_'+index"
radius="100"
:center="infoWindow.position"
/>

Show specific countries name on map

I am creating project using JavaScript. In my project I have integrated google map.My requirement is i want to show only some specific countries like:
India
USA
Australia
Currently I am hiding all countries using:
var emptyStyles =
[
{
featureType: "all",
elementType: "labels",
stylers: [ { visibility: "off" } ]
}
];
map.setOptions({styles: emptyStyles});
I have created plunker:
https://plnkr.co/edit/ZQIFZelNROkZcnFZ6mgB?p=preview
I found an example where specific cities were displayed on the map. The idea is to
hide all the labels(like you already did)
create a json array of the place that you want to show labels
for
Iterate through the json array and mark the labels.
You can find the code here: Display labels only to specific cities in Google Maps
Make following changes to the array:
var citiesJSON = {
geonames: [{
lat: 20.5937,
lng: 78.9629,
name: "India"
}, {
lat: 37.0902,
lng: -95.7129,
name: "USA"
}, {
lat: -25.2744,
lng: 133.7751,
name: "Australia"
}]
};

different markers groups in leaftlet

I am using Angular and leaflet and want to build a map with different markers, eg.: ships and bridges. I want to update them individually without removing and setting all markers again. So when I have new ships, I just want to call the ship markers, update them and the bridge markers stay the same.
Right now, I tried something like this:
angular.module('angularMapApp')
.controller('MainCtrl', ['$scope', 'RequestService', 'setShipMarkers', '$q', function($scope, RequestService, setShipMarkers, $q) {
angular.extend($scope, {
hamburg: {
lat: 53.551086,
lng: 9.993682,
zoom: 13
},
markers: {
ships: {
m1: {
lat: 42.20133,
lng: 2.19110
},
m2: {
lat: 42.21133,
lng: 2.18110
}
},
bridges: {
m3: {
lat: 42.19133,
lng: 2.18110
},
m4: {
lat: 42.3,
lng: 2.16110
}
}
},
defaults: {
tileLayer: 'http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png',
zoomControlPosition: 'topright',
tileLayerOptions: {
opacity: 0.9,
detectRetina: true,
reuseTiles: true,
},
scrollWheelZoom: false
}
});
But this does not works, as I get the following error (after setting markers-nested: true in my view):
You must add layers to the directive if the markers are going to use
this functionality.
However why do I need layers, if I just want to call different markers group on the same layer. I just do not want to update all of them at once.
So maybe someone can tell me, how to get separate marker groups and how to call them to update them.
For each kind of nested marker you have to create its own group layer like this, they can be empty:
layers: {
overlays: {
ships: { // use the same name as in the marker object
name: "Ships",
type: "group",
visible: true
},
bridges: { // use the same name as in the marker object
name: "bridges",
type: "group",
visible: true
}
}
}
By doing that you will also have to move the OSM base layer into the layers.baselayers object, but markers-nested="true" works this way.
Demo: http://plnkr.co/edit/HQx8bQmmsFUGcLxYt95N?p=preview

Adding Custom Markers to Custom Styled Google Maps API v3 for Wordpress website

Hi Everybody!
I am trying to create a Custom Styled Google map using API v3. The map will eventually go on the following Wordpress page (310px x 537px blank space on right side of page): http://www.flatschicago.com/edgewater-chicago-apartments/
I have copied the JavaScript/HTML code from the Google Maps Javascript API v3—Simple styled maps page, and have change the color scheme to fit my websites overall theme. I have managed to format the code with the colors that I want, and I have managed to format the size of the map so it fits the space designated on my web page.
Here are the 3 things that I am having issues with:
I want to add 5+ custom plot markers to the map. Where do I add this code?
I want the street labels to appear on the map. Where do I add this code?
I tried adding the code in to my Wordpress page, but I did not work. Is there a certain part of the JavaScript/HTML code that I should only be adding?
Here is the code that I have so far.
<html>
<head>
<title>Simple styled maps</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&sensor=false"></script>
<script>
var map;
var edgewater = new google.maps.LatLng(41.987245, -87.661233);
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
var featureOpts = [
{
stylers: [
{ hue: '#3b3d38' },
{ visibility: 'simplified' },
{ gamma: 0.5 },
{ weight: 0.5 }
]
},
{
featureType: 'poi.business',
elementType: 'labels',
stylers: [
{ visibility: 'off' }
]
},
{
featureType: 'water',
stylers: [
{ color: '#3b3d38' }
]
}
];
var mapOptions = {
zoom: 12,
center: edgewater,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID]
},
mapTypeId: MY_MAPTYPE_ID
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var styledMapOptions = {
name: 'Custom Style'
};
var customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions);
map.mapTypes.set(MY_MAPTYPE_ID, customMapType);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload='intialize()'>
<div id="map-canvas" style='width:310px; height:537px;'></div>
</body>
</html>
1) Adding 5+ Custom Plot Markers
The code I am referring to is from the following page: page link.
I understand that I need to add a marker image and long/lat for each location, but when I try and copy and paste this code into the code that I already have created, the map doesn't work. Where am I supposed to be copying and pasting this code? Do it go inside the function initialize() code? Or is it its own function? Very confused.
2) Adding Street Labels
The code I am referring to is from the Google Maps Javascript API v3—Styled Maps page.
All I want to do is to be able to see the street labels on the map. The code I am referring to is this. I tried putting this in to my code, but again, it didn't work. Is there a simply label like 'roads,' 'on' that gets these labels to work?
var styleArray = [
{
featureType: "all",
stylers: [
{ saturation: -80 }
]
},{
featureType: "road.arterial",
elementType: "geometry",
stylers: [
{ hue: "#00ffee" },
{ saturation: 50 }
]
},{
featureType: "poi.business",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
3) Add code to Wordpress page
The map will eventually go on the /edgewater-chicago-apartments/ pahe.
The space that I left for the map is labeled
<td class="neighborhood-map" rowspan="5"></td> :
If someone could please help me with this, I will be forever grateful. I feel like I am so close, yet these three things are holding me up and it is very frustrating. Anyone?
You need to have actual data (JSON format) to add the markers. For example:
// yourJsonData = data in valid JSON format
for ( i = 0; i < yourJsonData.length; i++ ) {
var latlng = new google.maps.LatLng(yourJsonData[ i ].lat, yourJsonData[ i ].long);
var marker = new google.maps.Marker({
map: map,
icon: yourURL + '/path-to-custom-markers/' + yourJsonData[ i ].icon,
position: latlng,
title: yourJsonData[ i ].title,
html: '<div class="info-window">Your window text</div>'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.html);
infowindow.setOptions({maxWidth: 800});
infowindow.open(map, this);
});
}
This code loops an array (yourJsonData) that has values for latitude, longitude, etc.

Categories