Difficulty changing style of google map on button click - javascript

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'), {

Related

Adding Multiple Markers on Vue JS Google Maps

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);
});

How can I hide street names in Google Maps JS API? [duplicate]

This question already has answers here:
google maps api v3 no labels?
(2 answers)
Closed 3 years ago.
I want to remove all the street names and pins of various places (e.g. museums, restaurants, and other spots) in Google Maps by using JS API.
Basically, all I need is just a map with no labels at all.
I assume it should be possible. How can I achieve it?
Here is the image of what I want to remove for better clarification.
Yes you can hide the labels which you don't require to display in map
<html>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.86, lng: 151.209},
zoom: 13,
mapTypeControl: false
});
map.setOptions({styles: styles['hide']});
}
var styles = {
hide: [
{
featureType: 'poi.business',
stylers: [{visibility: 'off'}]
},
{
featureType: 'transit',
elementType: 'labels.icon',
stylers: [{visibility: 'off'}]
}
]
};
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</script>
</body>
</html>
Still you can have granule control on the label type, to know more about all styles just read here: https://mapstyle.withgoogle.com/

Adding setVisible() to markers created in a map

I am creating a neighbourhood map using google maps API.I have added some locations and created markers. I want to add a search filter feature, such that the user can search those locations by their name. It should include a text input field or drop-down menu that filters the map markers and list items to locations matching the text input or selection.
The list items filtering works fine but the markers(locations) are not filtered.
So I want to ask how can I use setVisible() property to hide and display the markers in my code.
This is the filter module:
function viewModel(markers) {
var self = this;
self.filter = ko.observable(''); // this is for the search box
self.items = ko.observableArray(locations);
self.filteredItems = ko.computed(function() {
var filter = self.filter().toLowerCase();
if (!filter) {
return self.items();
} else {
return ko.utils.arrayFilter(self.items(), function(id) {
return stringStartsWith(id.title.toLowerCase(), filter);
});
}
});
This is the full code of my .js file.
var map;
var locations = [
{title: 'The Red Fort', location: {lat: 28.6562, lng: 77.2410}},
{title: 'Humayun\'s Tomb', location: {lat: 28.5933, lng: 77.2507}},
{title: 'India Gate', location: {lat: 28.6129, lng: 77.2295}},
{title: 'Lotus Temple', location: {lat: 28.5535, lng: 77.2588}},
{title: 'Akshardham Temple', location: {lat: 28.6127, lng: 77.2773}},
{title: 'Lodhi Gardens', location: {lat: 28.5931, lng: 77.2179}},
{title: 'Raj Ghat', location: {lat: 28.6406, lng: 77.2495}},
{title: 'Jama Masjid', location: {lat: 28.6507, lng: 77.2334}},
{title: 'Gurudwara Bangla Sahib', location: {lat: 28.6264, lng:
77.2091}},
{title: 'Qutub Minar', location: {lat: 28.5244, lng: 77.1855}},
];
var center =[{lat : 28.5244, lng : 77.1855}];
var markers = []; // Creating a new blank array for all the listing markers.
var styles = [
{
featureType: 'water',
stylers: [
{ color: '#19a0d8' }
]
},{
featureType: 'administrative',
elementType: 'labels.text.stroke',
stylers: [
{ color: '#ffffff' },
{ weight: 6 }
]
},{
featureType: 'administrative',
elementType: 'labels.text.fill',
stylers: [
{ color: '#e85113' }
]
},{
featureType: 'road.highway',
elementType: 'geometry.stroke',
stylers: [
{ color: '#efe9e4' },
{ lightness: -40 }
]
},{
featureType: 'transit.station',
stylers: [
{ weight: 9 },
{ hue: '#e85113' }
]
},{
featureType: 'road.highway',
elementType: 'labels.icon',
stylers: [
{ visibility: 'off' }
]
},{
featureType: 'water',
elementType: 'labels.text.stroke',
stylers: [
{ lightness: 100 }
]
},{
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [
{ lightness: -100 }
]
},{
featureType: 'poi',
elementType: 'geometry',
stylers: [
{ visibility: 'on' },
{ color: '#f0e4d3' }
]
},{
featureType: 'road.highway',
elementType: 'geometry.fill',
stylers: [
{ color: '#efe9e4' },
{ lightness: -25 }
]
}
];
function initMap() {
// Constructor creates a new map
map = new google.maps.Map(document.getElementById('map'), {
center: center[0],
zoom: 13,
styles: styles,
mapTypeControl: false
});
var largeInfowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var defaultIcon = makeMarkerIcon('0091ff'); // this is the default marker icon.
var highlightedIcon = makeMarkerIcon('FFFF24'); // this is the state of the marker when highlighted.
var activeIcon = makeMarkerIcon('0F0');
for (var i = 0; i < locations.length; i++) {
var position = locations[i].location; // Get the position from the location array.
var title = locations[i].title;
marker(locations);
}
// Create a marker per location, and put into markers array.
function marker(locations)
{var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
animation: google.maps.Animation.DROP,
id: i,
});
locations[i].marker = marker; // we made marker a property of the locations and stored info of each marker
wikiLink(locations[i]);
markers.push(marker); // Push the marker to our array of markers.
// Create an onclick event to open an infowindow at each marker.
marker.addListener('click', function() {
populateInfoWindow(this, largeInfowindow);
this.setIcon(activeIcon);
});
bounds.extend(markers[i].position);
/*
marker.addListener('mouseover', function() {
this.setIcon(highlightedIcon);
});
*/
marker.addListener('mouseout', function() {
this.setIcon(defaultIcon);
});
}
// Extend the boundaries of the map for each marker
map.fitBounds(bounds);
function wikiLink(location) {
location.url = '';
var wikiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' + title + '&format=json&callback=wikiCallback';
//If you cant get a wiki request, throw an error message.
/*
var wikiError = setTimeout(function() {
location.url = 'Unable to find the request';
}, 8000);
*/
$.ajax({
url: wikiUrl,
dataType: "jsonp",
jsonp: "callback",
success: function(response) {
console.log(response);
var url = response[3][0];
console.log(url);
location.marker.wikiurl = url;
console.log(location.url);
//clearTimeout(wikiError);
}
})
.fail(function (jqXHR, textStatus, error) {
error = 'Unable to find the request';
alert("Post error: " + error);
});
}
}
// This function populates the infowindow when the marker is clicked. We'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.setContent(''); // Clearing the infowindow content to give the streetview time to load.
infowindow.marker = marker;
// Making sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function() {
infowindow.marker = null;
});
// In case the status is OK, which means the pano was found, computing the position of the streetview image, then calculate the heading, then get a
// panorama from that and set the options
var getStreetView = function(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var nearStreetViewLocation = data.location.latLng;
var heading = google.maps.geometry.spherical.computeHeading(
nearStreetViewLocation, marker.position);
infowindow.setContent('<div>' + marker.title + '</div><hr><div id="pano"></div><div><a href=' + marker.wikiurl + '> Click here for more info </a></div>');
var panoramaOptions = {
position: nearStreetViewLocation,
pov: {
heading: heading,
pitch: 30
}
};
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), panoramaOptions);
} else {
infowindow.setContent('<div>' + marker.title + '</div><hr>' + '<div>No Street View Found</div>');
}
};
var streetViewService = new google.maps.StreetViewService();
var radius = 500;
// Use streetview service to get the closest streetview image within 50 meters of the markers position
streetViewService.getPanoramaByLocation(marker.position, radius, getStreetView);
infowindow.open(map, marker); // Open the infowindow on the correct marker.
}
}
// This function takes in a COLOR, and then creates a new marker icon of that color.
// The icon will be 21 px wide by 34 high, have an origin of 0, 0 and be anchored at 10, 34).
function makeMarkerIcon(markerColor) {
var markerImage = new google.maps.MarkerImage(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|'+ markerColor +
'|40|_|%E2%80%A2',
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34),
new google.maps.Size(21,34));
return markerImage;
}
function viewModel(markers) {
var self = this;
self.filter = ko.observable(''); // this is for the search box, takes value in it and searches for it in the array
self.items = ko.observableArray(locations); // we have made the array of locations into a ko.observableArray
self.filteredItems = ko.computed(function() {
var filter = self.filter().toLowerCase();
if (!filter) {
return self.items();
} else {
return ko.utils.arrayFilter(self.items(), function(id) {
return stringStartsWith(id.title.toLowerCase(), filter);
});
}
});
var stringStartsWith = function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
};
// this should show the infowindow if any place on the list is clicked
this.showInfoWindow = function(place) {
google.maps.event.trigger(place.marker, 'click');
};
}
$(function(){
ko.applyBindings(new viewModel());
});
This is .html file
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Map of my favourite city - New Delhi</title>
<link href="css/map_styles.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/knockout-3.4.1.js"></script>
</head>
<body>
<div id="mySidenav" class="sidenav">
<span class="menu-title">List of places</span>
<input type="text" data-bind="textInput: filter" placeholder="Search from the list">
<ul class="" style="list-style-type: none;" data-bind="foreach: filteredItems">
<li>
<span data-bind="text: title, click: $parent.showInfoWindow"></span>
</li>
</ul>
×
</div>
<div id="main">
<h2>Famous places in New Delhi</h2>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ Click here</span>
</div>
<div id="map"></div>
<div id="map-error" class="map-error"></div>
<script src="js/newmap.js"></script>
<script src="js/maperror.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCwUdUoC9ZiRbFC3et89fPK3tXIVO8D2sI&callback=initMap"
onerror="mapError()"></script>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</script>
</body>
</html>
Thanks for this question :) It was an interesting exercise. I'm not sure my answer will satisfy you, because it re-initializes the map every time a filter is done. I'm not sure how to get around that, because the viewModel and the initMap method are separate. But it does what you asked for.
Modified your initMap() method to take an array parameter, holding boolean values. If the array is not defined the markers' visibility are defaulted to true
Modified the viewModel, by creating an array to hold boolean values. The array is emptied every time the viewModel is called, and the markers are spliced to hold the original values only (One of the areas I'm sure you can improve on). Inside your ko.utils.arrayFilter() method, if returned value is true, I push a true value to the array as well. At the end of the array, I call the initMap() method again, with this array as input. Now only the locations which are filtered out as true in the search will be visible on re-initializing.
While applying the bindings I provided markers variable as input to the viewModel. (I think you had already intended to do this, but forgot).
Update:
Concerning the error you're getting in the comment, it's because I replaced your lines
<script src="js/newmap.js"></script>
<script src="js/maperror.js"></script>
with an empty <script> tag and placed the entire JS code in there. To avoid confusion, I'll remove all the snippets of code I had put above and show the entire file here:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript' src='knockout-3.4.2.js'></script>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="mySidenav" class="sidenav">
<span class="menu-title">List of places</span>
<input type="text" data-bind="textInput: filter" placeholder="Search from the list">
<ul class="" style="list-style-type: none;" data-bind="foreach: filteredItems">
<li>
<span data-bind="text: title, click: $parent.showInfoWindow"></span>
</li>
</ul>
×
</div>
<div id="main">
<h2>Famous places in New Delhi</h2>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ Click here</span>
</div>
<div id="map"></div>
<div id="map-error" class="map-error"></div>
<script>
var map;
var locations = [
{title: 'The Red Fort', location: {lat: 28.6562, lng: 77.2410}},
{title: 'Humayun\'s Tomb', location: {lat: 28.5933, lng: 77.2507}},
{title: 'India Gate', location: {lat: 28.6129, lng: 77.2295}},
{title: 'Lotus Temple', location: {lat: 28.5535, lng: 77.2588}},
{title: 'Akshardham Temple', location: {lat: 28.6127, lng: 77.2773}},
{title: 'Lodhi Gardens', location: {lat: 28.5931, lng: 77.2179}},
{title: 'Raj Ghat', location: {lat: 28.6406, lng: 77.2495}},
{title: 'Jama Masjid', location: {lat: 28.6507, lng: 77.2334}},
{title: 'Gurudwara Bangla Sahib', location: {lat: 28.6264, lng:
77.2091}},
{title: 'Qutub Minar', location: {lat: 28.5244, lng: 77.1855}},
];
var center = [{lat: 28.5244, lng: 77.1855}];
var markers = []; // Creating a new blank array for all the listing markers.
var styles = [
{
featureType: 'water',
stylers: [
{color: '#19a0d8'}
]
}, {
featureType: 'administrative',
elementType: 'labels.text.stroke',
stylers: [
{color: '#ffffff'},
{weight: 6}
]
}, {
featureType: 'administrative',
elementType: 'labels.text.fill',
stylers: [
{color: '#e85113'}
]
}, {
featureType: 'road.highway',
elementType: 'geometry.stroke',
stylers: [
{color: '#efe9e4'},
{lightness: -40}
]
}, {
featureType: 'transit.station',
stylers: [
{weight: 9},
{hue: '#e85113'}
]
}, {
featureType: 'road.highway',
elementType: 'labels.icon',
stylers: [
{visibility: 'off'}
]
}, {
featureType: 'water',
elementType: 'labels.text.stroke',
stylers: [
{lightness: 100}
]
}, {
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [
{lightness: -100}
]
}, {
featureType: 'poi',
elementType: 'geometry',
stylers: [
{visibility: 'on'},
{color: '#f0e4d3'}
]
}, {
featureType: 'road.highway',
elementType: 'geometry.fill',
stylers: [
{color: '#efe9e4'},
{lightness: -25}
]
}
];
function initMap(array) {
// Constructor creates a new map
map = new google.maps.Map(document.getElementById('map'), {
center: center[0],
zoom: 13,
styles: styles,
mapTypeControl: false
});
var largeInfowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var defaultIcon = makeMarkerIcon('0091ff'); // this is the default marker icon.
var highlightedIcon = makeMarkerIcon('FFFF24'); // this is the state of the marker when highlighted.
var activeIcon = makeMarkerIcon('0F0');
for (var i = 0; i < locations.length; i++) {
var position = locations[i].location; // Get the position from the location array.
var title = locations[i].title;
marker(locations);
}
// Create a marker per location, and put into markers array.
function marker(locations)
{
var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
animation: google.maps.Animation.DROP,
id: i,
visible: (array ? array[i] : true)
});
locations[i].marker = marker; // we made marker a property of the locations and stored info of each marker
wikiLink(locations[i]);
markers.push(marker); // Push the marker to our array of markers.
// Create an onclick event to open an infowindow at each marker.
marker.addListener('click', function () {
populateInfoWindow(this, largeInfowindow);
this.setIcon(activeIcon);
});
bounds.extend(markers[i].position);
/*
marker.addListener('mouseover', function() {
this.setIcon(highlightedIcon);
});
*/
marker.addListener('mouseout', function () {
this.setIcon(defaultIcon);
});
}
// Extend the boundaries of the map for each marker
map.fitBounds(bounds);
function wikiLink(location) {
location.url = '';
var wikiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' + title + '&format=json&callback=wikiCallback';
//If you cant get a wiki request, throw an error message.
/*
var wikiError = setTimeout(function() {
location.url = 'Unable to find the request';
}, 8000);
*/
$.ajax({
url: wikiUrl,
dataType: "jsonp",
jsonp: "callback",
success: function (response) {
console.log(response.length);
var url = response[3][0];
//console.log(url);
location.marker.wikiurl = url;
//console.log(location);
//clearTimeout(wikiError);
}
})
.fail(function (jqXHR, textStatus, error) {
error = 'Unable to find the request';
alert("Post error: " + error);
});
}
}
// This function populates the infowindow when the marker is clicked. We'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.setContent(''); // Clearing the infowindow content to give the streetview time to load.
infowindow.marker = marker;
// Making sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function () {
infowindow.marker = null;
});
// In case the status is OK, which means the pano was found, computing the position of the streetview image, then calculate the heading, then get a
// panorama from that and set the options
var getStreetView = function (data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var nearStreetViewLocation = data.location.latLng;
var heading = google.maps.geometry.spherical.computeHeading(
nearStreetViewLocation, marker.position);
infowindow.setContent('<div>' + marker.title + '</div><hr><div id="pano"></div><div><a href=' + marker.wikiurl + '> Click here for more info </a></div>');
var panoramaOptions = {
position: nearStreetViewLocation,
pov: {
heading: heading,
pitch: 30
}
};
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), panoramaOptions);
} else {
infowindow.setContent('<div>' + marker.title + '</div><hr>' + '<div>No Street View Found</div>');
}
};
var streetViewService = new google.maps.StreetViewService();
var radius = 500;
// Use streetview service to get the closest streetview image within 50 meters of the markers position
streetViewService.getPanoramaByLocation(marker.position, radius, getStreetView);
infowindow.open(map, marker); // Open the infowindow on the correct marker.
}
}
// This function takes in a COLOR, and then creates a new marker icon of that color.
// The icon will be 21 px wide by 34 high, have an origin of 0, 0 and be anchored at 10, 34).
function makeMarkerIcon(markerColor) {
var markerImage = new google.maps.MarkerImage(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|' + markerColor +
'|40|_|%E2%80%A2',
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34),
new google.maps.Size(21, 34));
return markerImage;
}
function viewModel(markers) {
var self = this;
self.filter = ko.observable(''); // this is for the search box, takes value in it and searches for it in the array
self.items = ko.observableArray(locations); // we have made the array of locations into a ko.observableArray
var arrayofMarkersForVisibility = [];
self.filteredItems = ko.computed(function () {
if (markers.length>10) markers.splice(10,10);
var filter = self.filter().toLowerCase();
if (!filter || filter =="") {
arrayofMarkersForVisibility = [];
for (var i in markers){
//markers[i].setVisible(true);
arrayofMarkersForVisibility.push(true);
}
initMap(arrayofMarkersForVisibility);
return self.items();
} else {
arrayofMarkersForVisibility = [];
for (var i in markers){
arrayofMarkersForVisibility.push(false);
//markers[i].setVisible(false);
}
return ko.utils.arrayFilter(self.items(), function (id) {
var somestring = stringStartsWith(id.title.toLowerCase(), filter);
if (somestring){
arrayofMarkersForVisibility[id.marker.id]=true;
//markers[i].setVisible(true);
}
if (id.marker.id ==markers.length-1) initMap(arrayofMarkersForVisibility);
return somestring;
});
}
});
var stringStartsWith = function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
};
// this should show the infowindow if any place on the list is clicked
this.showInfoWindow = function(place) {
google.maps.event.trigger(place.marker, 'click');
};
}
$(function(){
ko.applyBindings(new viewModel(markers));
});
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCwUdUoC9ZiRbFC3et89fPK3tXIVO8D2sI&callback=initMap"></script>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</script>
</body>
</html>

How to set Google Maps styles dynamically

Using the Google Map APi v3 , there are style options such as :
{
featureType: 'transit.line',
elementType: 'geometry',
stylers: [
{ hue: '#fc0101' },
{ visibility: 'on' }
]
}
This works on map load, as can be seen in the API example: https://developers.google.com/maps/documentation/javascript/examples/maptype-styled-simple
I need to add a click event to show or change a certain style, for example if I change the above codes hue value on a dom event.
Example code:
// a link to test map changes
var testDiv = document.getElementById("test");
// add click event listener for map
google.maps.event.addDomListener(testDiv, 'click', showTest);
// the function for setZoom works
function showTest() {
map.setZoom(2);
}
I cannot find any documents for setting the style, there is no "set", https://developers.google.com/maps/documentation/javascript/reference#StyledMapType
There is setOptions which includes a styles property but I cannot get it to work.
An example that does not work:
// turn off transit line visibility on click
function showTest() {
map.setOptions({
styles : {
featureType: 'transit.line',
elementType: 'geometry',
stylers: [
{ hue: '#fc0101' },
{ visibility: 'off' }
]
}
});
}
Working example with zoom event (just zooms out map):
http://codepen.io/anon/pen/yfGxm
Non Working example with style event (this is set to remove the
transit line shown in black): http://codepen.io/anon/pen/CphbA
Edit: The answer below is great and I didn't realize this is also documented here: https://developers.google.com/maps/documentation/javascript/styling?csw=1
http://codepen.io/jolsalazar/full/anKqG
Here the example code:
var map;
var chicago = new google.maps.LatLng(41.850033, -87.650052);
function initialize() {
var roadAtlasStyles = [
{
featureType: 'transit.line',
elementType: 'geometry',
stylers: [
{ hue: '#ff0000' },
{ visibility: 'on' },
{ lightness: -70 }
],
enableCloseButton: true,
visible: false
}
];
var mapOptions = {
zoom: 12,
center: chicago,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'usroadatlas']
}
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var styledMapOptions = {
name: 'US Road Atlas'
};
var usRoadMapType = new google.maps.StyledMapType(
roadAtlasStyles, styledMapOptions);
map.mapTypes.set('usroadatlas', usRoadMapType);
map.setMapTypeId('usroadatlas');
google.maps.event.addDomListener(document.getElementById('test'), 'click', function() {
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
});
}
jQuery(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initialize);
});
For me, map.setOptions() works well for setting styles.
I think you forgot the [ ] brackets.
You can change map style as followed:
// turn off transit line visibility on click
function showTest() {
var myStyle =[{
featureType: 'transit.line',
elementType: 'geometry',
stylers: [
{ hue: '#fc0101' },
{ visibility: 'on' }
]
}];
map.setOptions({styles: myStyle});
}

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