How to set Google Maps styles dynamically - javascript

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

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

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>

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.

Can I hide non-seas/oceans on Google Maps Styling API

I am double checking, really, as I think the answer is no: Can I hide bodies of water which aren't seas/oceans, i.e. lakes. A client is commenting that these smaller bodies of water make the maps look "complicated".
Here's my styling rules:
fsdStyles = [
{
featureType: 'all',
stylers: [
{visibility: 'off'},
{hue: '#00162b'}
]
},
{
featureType: 'administrative.country',
stylers: [
{ visibility: 'on' }
]
},
{
featureType: 'water',
stylers: [
{ hue: '#002f56' },
{ saturation: 85 },
{ lightness: -84 },
{ visibility: 'simplified' }
]
}
];
No, you cannot turn the features you describe off. And there is only the single feature type: water, there are no sub-types, so there is no real way to style lakes in one way and oceans in another.

catching javascript "unexpected end of input"

This is a view in a rails app - unfortunately I am getting an error I cannot fix ("Uncaught Syntax Error: Unexpected end of input"). Although I'm sure the answer is simple, adding an extra }); does not solve the problem.
Anyone have any thoughts as to where I may have forgotten to close something out?
Thanks!
In HAML:
- content_for :before_head do
= javascript_include_tag "http://maps.google.com/maps/api/js?sensor=false"
- content_for :page_javascript do
= javascript_include_tag "http://www.mapnificent.net/media/api/1/mapnificent.js"
:javascript
var MAP, HEATMAP, DATAPOINTS;
var mapnificent, urbanDistance, positions = {};
$(document).ready(function() {
DATAPOINTS = {};
var myLatlng = new google.maps.LatLng(40.75297891717686, -73.93936157226562);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: true,
draggable: true,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
disableDoubleClickZoom: false,
streetViewControl: false,
mapTypeControl: false,
overviewMapControlOptions: false,
styles: [
{
featureType: "administrative",
elementType: "geometry",
stylers: [
{ visibility: "off" }
]
},{
featureType: "administrative.locality",
stylers: [
{ visibility: "on" }
]
},{
featureType: "transit.line",
stylers: [
{ visibility: "off" }
]
},{
elementType: "geometry",
stylers: [
{ saturation: -100 },
{ lightness: -100 },
{gamma:0.24}
]
},{
featureType: "road.arterial",
elementType:"labels",
stylers: [
{ visibility: "simplified" },
// { saturation: -100 },
// {lightness:70},
// {hue: "#ffc243"}
]
},{
featureType: "road.highway",
elementType: "labels",
stylers: [
{ visibility: "simplified" },
// { saturation: -100 },
// {lightness:70},
// {gamma: 0},
]
},{
featureType: "landscape",
elementType: "geometry",
stylers: [
{ lightness: 92 },
{ saturation: 20 },
{ hue: "#e2ded3" },
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ visibility: "simplified"},
{ saturation: 10 },
{ lightness: 100 },
{ hue: "#ffc243" }
]
},{
featureType: "water",
stylers: [
{ visibility: "simplified" },
{ lightness: 70 },
{ saturation: 15 },
{ hue: "#00ffdd" }
]
},{
featureType: "poi",
elementType: "geometry",
stylers: [
{ visibility: "on" },
{ saturation: 15 },
{ lightness: 89 },
{ hue: "#e2ded3" }
]
},{
featureType: "transit.station",
elementType: "geometry",
stylers: [
{ visibility: "simplified" },
{ lightness: 85 },
{ hue: "#e2ded3" },
{ saturation: 15 }
]
},
{
featureType: "poi.park",
elementType: "geometry",
stylers: [
{ hue: "#61bb00" },
{ lightness: -15},
{ saturation: 20},
{ visibility: "simplified" }
]
},{
featureType: "transit.station",
elementType: "labels",
stylers: [
{ hue: "#06bca9" },
{ saturation: -30},
{ lightness: -10},
{ visibility: "on" }
]
}
]
};
MAP = new google.maps.Map(document.getElementById("map"), myOptions);
/*
This is the UrbanDistance's (i.e. the public transport layer) UI function.
This function gets called during the setup process and you can easily setup your UI in there
Parameters:
mapnificent: the mapnificent instance, responsible for how to draw on the map
that: the urbanDistance layer object, responsible for handling the public transport travel time calculation and drawing
$: jQuery for your convenience, scoped to this function, shortcut to window
undefined: the real undefined value, only 4 arguments are passed
*/
var UrbanDistanceUI = function(mapnificent, that, $, window, undefined){
/* that.bind binds a function to an event of the layer
setup is called when the setup of the layer is complete
and before the loading of necessary data.
*/
that.bind("setup", function(){
/* There are many options for the public transport layer
They can be read with .getOption and set with .setOption */
var color = that.getOption("color");
that.setOption("color", true);
/* you must display this copyright notice somewhere on your page */
$("#copyright").html(that.getOption("copyright"));
console.log("setup done");
});
/*
loadProgress binds to the data loading progress,
you will receive one parameter: a percentage */
that.bind("loadProgress", function(progress){
$('#loading').text(progress);
if(progress >= 100){
$('#loading').text("Almost done...");
}
});
/*
fires when the data has finished loading */
that.bind("dataLoaded", function(){
$('#loading').text("Done!");
var geopos = {lat:40.75297891717686,lng:-73.93936157226562}, time = 30 * 60;
/* adds a position to the map at the specificed location.
Time can be left out for the default time (15 minutes) */
var pos = that.addPosition(geopos, time); // time in seconds!
/* The call returns a position object that you can store.
You can store it by it's index pos.index */
positions[pos.index] = {position: pos, latlng: geopos};
/* You only created a position, you need to start the
calculation process explicitly */
pos.startCalculation();
});
/* fires when a calculation has started, receives position as parameter */
that.bind("calculationStarted", function(position){
$('#loading').text("Starting calculation: 0.0%");
});
/* fires when there is a calculation progress, receives position as parameter */
that.bind("calculationUpdated", function(position){
/* estimating the progress is not an exact since
the option value "estimatedMaxCalculateCalls" is
an estimated upper bound of position.calculationProgress
*/
var percent = position.calculationProgress /
that.getOption("estimatedMaxCalculateCalls") * 100;
$('#loading').text("Calculating: "+percent+"%");
});
/*fires when the calculation is done */
that.bind("calculationDone", function(position){
$('#loading').text("Calculation Done!");
console.log("done");
/* you need to trigger a redraw of the canvas yourself at appropriate moments */
mapnificent.trigger("redraw");
/* see getBlobs function further down */
getBlobs();
});
var movePosition = function(index, pos){
/* you can move your position with the .move method of a position
it takes an geo object {lat: X, lng:Y} as first parameter.
last parameter indicates if positionMoved should be triggered */
var result = positions[index].position.move(pos, true);
/* result indicates if the position is in range of the current city data
if it is not, positionMoved has not been triggered, regardless of second parameter
it it is true, postionMoved has been triggered (it already executed)
the latlng field of the position is set regardless of anything
*/
if (!result){
console.log("moved outside of range!");
}
};
/* triggered when a position moved inside the range */
that.bind("positionMoved", function(pos){
positions[pos.index].latlng = pos.latlng;
console.log("position move to ", pos.latlng);
});
var removePosition = function(index){
/* you can call removePosition on the UB layer with an index
to remove this position. This will also stop all ongoing calculations */
that.removePosition(index);
};
/* fires after successful removal */
that.bind("positionRemoved", function(index){
console.log("position removed");
delete startPositions[index];
mapnificent.trigger("redraw");
});
var getBlobs = function(){
/* A blob is a currently visible*, highlighted area that is
separate from other highlighted areas. The blob contains the
maxbounds in canvas coordinates, and some other information */
var blobs = that.search.detectBlobs();
console.log(blobs);
};
/* tried adding in a '}' here */
google.maps.event.addListenerOnce(MAP, "idle", function() {
HEATMAP = new HeatmapOverlay(MAP, {
"radius": 30,
"visible": true,
"opacity": 60
});
getDataPoints("theater", "http://doug.cartodb.com/api/v2/sql/?q=SELECT ST_x(geom) AS lng, ST_y(geom) AS lat, count(*) FROM (SELECT ST_SnapToGrid(the_geom,0.005) AS geom FROM v_theaters) AS foo GROUP BY lng, lat");
getDataPoints("noise", "http://doug.cartodb.com/api/v2/sql/?q=SELECT ST_x(geom) AS lng, ST_y(geom) AS lat, count(*) FROM (SELECT ST_SnapToGrid(the_geom,0.005) AS geom FROM noise) AS foo GROUP BY lng, lat");
getDataPoints("4sqDrug", "http://doug.cartodb.com/api/v2/sql/?q=SELECT ST_x(geom) AS lng, ST_y(geom) AS lat, count(*) FROM (SELECT ST_SnapToGrid(the_geom,0.005) AS geom FROM _4sq_15_32_47_drugstores_20or_20pharmacies) AS foo GROUP BY lng, lat");
});
if(typeof Mapnificent !== "undefined" && Mapnificent.isBrowserSupported()){
/* load Mapnificent options for these coordinates */
Mapnificent.forCoordinates({lat:40.75297891717686,lng:-73.93936157226562}, function(options){
if(options == null){
/* if null, there is no Mapnificent data for this point */
return;
}
/* if there are options, you can instantiate a new Mapnificent instance */
mapnificent = Mapnificent(options);
/* add the "urbanDistance" layer with the UI function */
mapnificent.addLayer("urbanDistance", UrbanDistanceUI);
/* you can bind to the initDone event of mapnificent */
mapnificent.bind("initDone", function(){
// mapnificent.hide();
});
/* finally add mapnificent to your map by passing the Google Maps instance */
mapnificent.addToMap(map);
});
}
/* tried removing a "});" from two lines below this comment */
});
function showHeatmap() {
var max = 0;
var all_points = [];
for(var key in DATAPOINTS ) {
DATAPOINTS[key].rows.forEach(function(row) {
if (row.count > max) {
max = row.count
}
});
all_points = all_points.concat(DATAPOINTS[key].rows);
}
var testData = {
max: max,
data: all_points
}
HEATMAP.setDataSet(testData);
}
function getDataPoints(name, url) {
$.get(url, function(data) {
DATAPOINTS[name] = data;
showHeatmap();
});
}
%b
#loading
#copyright
The error comes in here before this next chunk - Uncaught Syntax Error: Unexpected end of input
.map_holder{:style => "float: left; width: 600px; height: 600px;"}
#map{:style => "width: 100%; height: 100%; border: 1px solid #333;"}
.side_bar{:style => "float: right;"}
%p SideBar
= label_tag "Noise Data"
= check_box_tag "Test"
.cl{:style => "clear: both;"}
From the use of console.log(), I take it you're not testing in IE right now. But if the error was in IE, I would remove the trailing commas from the lines which say:
{ visibility: "simplified" },
In cases like this, the best debugging technique I know is doing a "binary search". Remove half the code (of course, don't just chop it off in a place which will leave unmatched brackets or braces), try running it in a browser, and see if there is still a syntax error. Repeat until you narrow it down to a small section of code.

Categories