Related
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'), {
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});
}
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.
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.
I can't properly set color of water with google maps api v3.
My RGB color is: #676a59. I've converted it to HSL using this tool: http://www.workwithcolor.com/hsl-color-picker-01.htm. The result is: color: hsl(71, 9%, 38%);
This is the code I use in Javascript to style water.
stylers: [{hue: "#676a59"}, {lightness: 38}, {saturation: 9}, {visibility: "on" }, {gamma: 1.0}]
The problem is that it doesn't work at all. I don't really know what is the reason of that. Can you see something that I'm doing wrong?
Thanks
When Google Maps API did not quite match the color I selected for a styled map, I I pulled up the map in a browser, took a screenshot of just the area with the two shades that weren't quite matching, opened that screenshot up in an image editor (pixlr.com, in my case), used the color-sucker tool to get the saturation and lightness for the shade that wasn't quite right, adjusted my saturation and/or lightness in my Google Maps APi call by 1 to get it closer to the saturation and/or lightness of the color I wanted, and repeated until I got something that matched. It was tedious--I ended up taking about a half dozen snapshots before it was perfect--but it worked.
I struggled with this for a long time, and tried two different Google Maps colour pickers without success.
However, the second one I tried alerted me to another way of specifying the colour: Rather than struggling with Google's take on HSL, you can just use the color property:
For example:
var mapStyles = [
{
featureType: "water",
stylers: [
{ color: '#b6c5dd' }
]
}
];
I did it like this and it is working.Take a look
var stylez = [{
featureType: "water",
elementType: "all",
stylers: [{
hue: "#006b33"
},
{
lightness: -70
},
{
saturation:100
}]
}];
//Map options
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'yourName']}
};
//Make a new map
map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);
var styledMapOptions = {
name: "yourName"
}
var yourNameMapType = new google.maps.StyledMapType(
stylez, styledMapOptions);
map.mapTypes.set('yourName', yourNameMapType);
map.setMapTypeId('yourName');