With Google's raster maps, I could create a map with an initial style like this (example taken from Google's documentation):
var mapStyles = [{ elementType: 'geometry', stylers: [{ color: '#242f3e' }]}];
var mapOptions = {
center: { lat: 40.674, lng: -73.945 },
zoom: 12,
styles: mapStyles
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions );
Then, I could change the style like this:
var newStyles = [{ elementType: 'geometry', stylers: [{ color: '#ffffff' }]}];
map.setOptions({ styles: newStyles });
With the vector based maps, instead of specifying the style in code, I need to specify a map ID. That map ID will have a style that someone configured in the cloud. I created two of these map IDs (a normal theme and a dark them) following the instructions here, and then instantiated my map like this:
var mapOptions = {
center: { lat: 40.674, lng: -73.945 },
zoom: 12,
mapId: 'abcd1234mymapid'
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions );
I tested both map IDs to be sure the theme was working. The problem is that I can't figure out how to change the map ID after creating the map. I want to allow the user to switch between map IDs. I tried:
// Does not work
map.setOptions({mapId: 'efgh5678myothermap'})
// Also does not work
map.mapId = 'efgh5678myothermap'
Is this functionality gone with Google's vector maps or am I doing it wrong?
I did make sure to include both map IDs when loading Google's script:
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&v=weekly&callback=yourInitMapMethod&map_ids=abcd1234mymapid,efgh5678myothermap"></script>
Currently, the only workaround to switch from one style to another (changing mapIds) is to create a new map instance. Note that each map instance is billed. As per Dynamic Maps Usage and Billing. You can do something like this:
//Event that triggers change of map style
document.getElementById("map_id_1").addEventListener("click", function(){
mapID = "YOUR_MAP_ID"
new google.maps.Map(document.getElementById("map"), {
...sharedOptions,
mapId: mapID,
useStaticMap: false
});
});
Here's a complete JSFiddle sample you can try.
Dynamically changing the mapId through the setOptions() function currently is not possible as it appears that mapId is not yet added as a property of the MapOptions interface as per the documentation.
I already filed a Feature Request in Google Maps Public issue tracker to support for this.
Related
I've made a Wordpress website with a template tool 'beaver builder'. That tool has a google map module, but that doesn't work very well. For example, I can't change to zoom level and center.
I also want to show a specific marker in a cluster.
This is the website page: http://www.depot-rato.be/het-project/
Is there a way to control the google map with some Javascript or jQuery?
jQuery('.gmap').setZoom(19);
Thanks in advance.
I've found a solution:
jQuery(document).ready(function($) {
var aLocation = { lat: 51.009054, lng: 4.509285};
$('.gmap').gmap('get','map').setOptions(
{
'zoom': 18,
'center': aLocation
}
);
});
I do it like this(at map initialization, resets the map and markers):
var aLocation= { lat: 48.4728146, lng: 7.499930100000029 };
map = new google.maps.Map(document.getElementById('myMap'), {
zoom: 5,
center: aLocation,
title: 'myMapTitle',
});
or like this(this one shouldn't initialize the map or markers):
map.setZoom(5);
map.setCenter(aLocation);
map.panTo(aLocation);// no need for this one, if you used the one above
You can try it here(click on the marker):
https://codepen.io/sam67/pen/KRGLjY
I am trying to make an AJAX map Google map, where the place markers update but not the map.
I have an ajax setup with a settimeout function, which returns new javascript. When the new javascript is loaded into my HTML, the changes do not reflect on my google map.
When I go into the firefox inspector and try and manipulate the javascript, (to try and change marker GPS coordinates), nothing happens to the map, and the points are still the same. Why does that not affect the map?
I have looked at several links to try and help me, but none of them explain the logic behind the javascript.
My PHP script returns javascript in plain text. But when these get
added to the HTML, The google map does not change and looks like it
needs to be re initialized before it recognizes new javascript?
Can someone explain how I should update the javascript, so the map re-centers on the newest marker and places the newest marker without refreshing the page / re initializing the map?
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: -20.530637, lng: 46.450046}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
new google.maps.LatLng("-21.530637,46.450046),
new google.maps.LatLng("-22.530637,46.450046),
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'content.php',
type:'POST',
success:function(results) {
locations=results;
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,5000);
</script>
My "content.php" file. returns more google maps LatLng markers in plain text.
so PHP output is:
new google.maps.LatLng("-23.530637,46.450046"),
new google.maps.LatLng("-24.530637,46.450046"),
new google.maps.LatLng("-25.530637,46.450046"),
new google.maps.LatLng("-26.530637,46.450046")
I would like to summary the behavior of your ajax map:
Initialize map (probably with a set of predefined locations)
Repeatedly call content.php to retrieve new update of markers
Draw new markers to your map
The problem is that your code that handles ajax result doesn't do any map manipulation. In fact, it has to update the variable locations with new location set. Then create new markers with updated list of locations, then call MarkerCluster to apply them.
I created a fiddle to demonstrate it: https://jsfiddle.net/anhhnt/paffzadz/1/
What I did is extract the marker creating part from initMap, so that it can be called multiple times after locations is updated.
function updateMarker () {
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
};
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
updateMarker(map);
};
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124}
]
function refresh_div() {
jQuery.ajax({
url:'/echo/json/',
type:'POST',
data: {
json: JSON.stringify([
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}
])
},
success:function(results) {
locations.concat(results);
updateMarker();
}
});
}
t = setInterval(refresh_div,5000);
Hope it helps.
Perhaps you have simple syntax error in your code - missing closing double quote:
new google.maps.LatLng("-23.530637,46.450046"),
...
..or better - remove first double quote:
new google.maps.LatLng(-23.530637,46.450046),
...
I am using Google Maps Javascript API v3,
What i would like to do is to highlight all routes within a specific circle radius when choosing a point in the map (point coordinates and circle radius are input parameters).
I tried to use the Directions Services and i did manage to display all possible routes when origin and destination points and travelMode are specified and the provideRouteAlternatives option is set to true.
When setting the origin point to be the cirle center, is there way to set multiple destinations points (points on the circle perimeter), and then loop over availables routes and highlight them using Directions Service?
P.S.: i am not trying to draw a circle around a point but to highlight all roads within the circle radius.
Thanks.
This is a just-for-fun answer.
Not really an answer because it really feels like a dirty little hack, and also I am not sure to understand what exactly you are trying to highlight (is it all streets or the results of a Directions request — this is unclear from your question).
But basically, I added 2 maps. The first one is the base map and the other one is positioned on top of the first one, with a border radius, and styles applied.
I then synchronize both maps so that they both move relatively (when panning / zooming).
var myLatlng = new google.maps.LatLng(51.51, -0.12);
var styles = [{
"featureType": "road",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ff3380"
}]
}];
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var roundedMapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
styles: styles
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var roundedMap = new google.maps.Map(document.getElementById("map-rounded"), roundedMapOptions);
google.maps.event.addListener(map, 'drag', function () {
roundedMap.setCenter(map.getCenter());
});
google.maps.event.addListener(roundedMap, 'drag', function () {
map.setCenter(roundedMap.getCenter());
});
google.maps.event.addListener(map, 'idle', function () {
roundedMap.setCenter(map.getCenter());
});
google.maps.event.addListener(map, 'zoom_changed', function () {
roundedMap.setZoom(map.getZoom());
});
Note on the use of the idle event listener:
If you are dragging the map very quickly, sometimes the sync is kind of lost. So with the idle event listener, the maps are re-synced after a drag.
Note that I added the below CSS rule to hide the copyright on the rounded map:
#map-rounded .gm-style-cc {
display: none;
}
This is clearly against Google Maps TOS but since it is still there on the base map, I would think this is a fair or acceptable misuse of the API :)
JSFiddle demo
Problem: I want to use a google maps v3 terrain map with own styles as an own mapType.
I started with this code:
var mapOptions = {
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.TERRAIN,
styles: styles
};
It shows my terrain with my own styles. Thats okay!
Now, i want too add this to the mapTypeIds
var styledMap = new google.maps.StyledMapType(styles, {
name: "NSW"
});
var mapOptions = {
scrollwheel: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'map_style']
}
};
var map = new google.maps.Map(map_id[0],
mapOptions);
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
The problem is, google maps uses "ROADMAP" for the "StyledMapType" and i've no idea how to change this to "TERRAIN". Is that even possible?
Update:
As you can see, "roadmap" is default. In the main.js from the google maps api there is the line:
k=c.baseMapTypeId||"roadmap"
So, what is the baseMapTypeId? The one, which i set in the mapOptions like:
mapTypeId: google.maps.MapTypeId.TERRAIN
???
May, this helps to solve my Problem.
You can do it this way:
var styles = [{
"stylers": [{
"saturation": -100
}]
}];
var styledMap = new google.maps.StyledMapType(styles, {
name: "Name of your style"
});
var myLatlng = new google.maps.LatLng(10, 10);
var map = new google.maps.Map(document.getElementById("map-canvas"), {
scrollwheel: false,
center: myLatlng,
zoom: 10
});
map.mapTypes.set('NSW', styledMap);
var mapTypeControlOptions = {
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'NSW']
}
};
map.setOptions(mapTypeControlOptions);
Note that the name of your StyledMapType is the name that will be displayed on the map, and the id of your MapStyle that you declare with the set method is what you need to use to reference your map style.
Hope this helps!
JSFiddle demo
Edit:
If you want to apply custom styles over the TERRAIN map style, you could do it by setting the styles of the current map type. You can add a custom control to your map to handle the toggling.
JSFiddle demo
It is possible to set a different base map for StyledMapType.
Note the second argument. You've actually figured this out by yourself, based on your screenshot and updated comment.
new google.maps.StyledMapType(styles, { baseMapTypeId: google.maps.MapTypeId.TERRAIN })
Previously, I would have gone to google, grabbed an iframe from the description of the organisation and simply pasted it into the page I was working on. The information box would show information about the business such as full address, phone number and website, etc. (see image below):
After deciding to redo my website from scratch I decided I would try to update the map as well. There were a couple of reasons for this. The new Google Maps looks more polished (personal preference) and using the API I could stylize the map to fit the color scheme of my site.
I started with a fairly simple bit of javascript:
function initialize(data) {
var map;
var someLoc = new google.maps.LatLng(####,#####);
var MY_MAPTYPE_ID = 'custom_style';
var featureOpts = [
{
"stylers": [
{ "hue": "#8800ff" },
{ "lightness": 33 }
]
}
]
var mapOptions = {
zoom: 12,
center: someLoc,
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);
}
$(document).ready(function(){
google.maps.event.addDomListener(window, 'load', initialize);
});
This gives me the following map:
However, I would like to display a marker for the business location and associated information so I add:
var marker = new google.maps.Marker({
position: someLoc,
map: map,
title: 'Hello World!'
});
}
But this means I get the organisation displayed on the map and the marker I have just created:
Is it possible to get the same result as the iframe (first image) using the Google Maps API (V3)? Essentially I would like to get to show the associated information of the business when the page loads so I have something similar to:
Okay, I found a fairly simple solution.
Set the maxZoom level so only the pin you create can be seen:
var mapOptions = {
zoom: 12,
maxZoom: 16,
center: myLoc,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID]
},
mapTypeId: MY_MAPTYPE_ID
};
Then add any other information using an information window.