Change Google Maps v3 mapOptions object after load - google-maps-api-3

How can i modify a V3 map's mapOptions (after the initial map has been loaded)?
Specifically, I would like to be able to flip the
draggable: false
option to
draggable: true
When an action (such as a click on a div) is triggered.
Addition: I have tried loading jquery-ui-map and using:
$('#map').gmap('option', 'draggable', true);
However this seems to reload the map and forget all the other existing options. I could redefine them all, but that seems a bit hackish.
Any pointers appreciated.
Thanks!

Found that I don't even need jQuery for this – it's already part of the Google Maps API. Simply do:
map.set('draggable', true);
Too easy! Hope it helps someone.
======
2020 update - you should use:
map.setOptions({ draggable: true });

Google Maps JavaScript API V3.25 update
Note that map.set() does not work in newer versions of Maps API. You have to use map.setOptions()
Source: Google Maps Reference

If you have already created the map previously, you can set several options ( https://developers.google.com/maps/documentation/javascript/reference#MapOptions ) at once like this:
var myOptions = {
zoom:11,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false
};
map.set(myOptions);

Related

google maps infoWindow click event re-renders map-canvas in Meteor

Hey Im trying to use google maps within my MeteorJS project to have google maps display on a map all customers, and then to display an infoWindow when you click on one of the markers.
problem is anytime you click on the marker it re-renders the map from scratch, i know this has to do with the the reactivity of the Session variable being set when the infoWindow is being clicked.
is there any way avoid the map being re-rendered when the session variable is changing?
thanks.
below is the JS and template im using in my project.
<template name="customers_map">
{{#constant}}
<div id="mapWrapper">
<div id="map-canvas"></div>
</div>
{{/constant}}
</template>
the code for making the google maps and markers.
Template.customers_map.rendered = function() {
$("#map-canvas").height("400px");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
Session.set("myLat", p.coords.latitude);
Session.set("myLng", p.coords.longitude);
});
}
Deps.autorun(function(){
var mapOptions = {
center: new google.maps.LatLng(Session.get("myLat"), Session.get("myLng")),
zoom: 15,
zoomControl: true,
zoomControlOptions: {style: google.maps.ZoomControlStyle.SMALL},
streetViewControl: false,
mapTypeControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.SMALL
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow({
content: Template.customers_infoWindow()
});
Customers.find().forEach(function(customer) {
if (customer.loc != null) {
var geo = customer.geoLocation();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(geo.lat, geo.lng),
title: customer.name(),
icon:'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
Session.set("customerId", customer._id);
infowindow.open(map,marker);
});
} else {
console.log(customer.name() + " has no geoLocation");
};
});
});
};
the infoWindow template
<template name="customers_infoWindow">
<h1>{{record.name}}</h1>
</template>
and the js for the infoWindow template
Template.customers_infoWindow.record = function() {
return Customers.findOne({_id: Session.get("customerId")});
}
If you create a global googlemaps object, you can access its properties from anywhere. This article has a nice example of doing this.
The overall gist is:
Create a googlemaps class with an initialize method. At the end of the initialize method, set a session variable for your map's existence. ( Session.set('map', true);)
Call create a googlemap object by calling the googlemap init method from within Template.customers_map.rendered.
It's a bit difficult to be sure without having a running version in front of me, but I think this is essentially because you have all your code in one big Deps.autorun block. Clicking one of the markers is changing the Session variable customerId, which will cause customers_infoWindow to re-render (as it's clearly a dependency), but I'm sure this is the intended behaviour.
However, since you're declaring var infoWindow in your Deps.autorun block to have an instance of that template as one of its properties, I think that changing customers_infoWindow will actually invalidate the entire Deps.autorun calculation, which means the whole block will be executed again, including the var map = new google.maps.Map(...) line, which will essentially re-render the map (even though it doesn't re-render that actual div element that contains it).
So, I would suggest splitting your code into separate Deps.autorun blocks, and making sure that anything in the same block should be re-run at the same time - clearly, this means that the Google Maps initialisation code and the infoWindow handler should be in separate blocks.
To reiterate, I think that's what's going on, but you'll have to try it and let me know...

Google Maps - all buttons are disabled on load

I'm writing a Wordpress page for a client that displays some text and a Google Map based on data loaded from a database.
So far I've gotten most of it to work. The Google Maps however begins to load then mysteriously "blues" out displaying only what looks like ocean with all the other options (zoom in/out, street view, etc.) greyed out.
There are no JavaScript errors available from FireBug etc.
The divs containing the map (#container, and #map-canvas ) are set to real pixel values.
The solution given here yields no positive results.
This is what the end result looks like:
Any ideas would be extremely welcome.
Edit:
Code snip per request:
echo '<script>function initialize(e,t,n){e=parseFloat(e);t=parseFloat(t);var r=new google.maps.LatLng(e,t);var i;var s;var o={center:r,zoom:14,mapTypeId:google.maps.MapTypeId.ROADMAP};s=new google.maps.Map(document.getElementById("map-canvas"),o);i=new google.maps.Marker({map:s,draggable:false,animation:google.maps.Animation.DROP,position:r,title:n});google.maps.event.addDomListener(window,"load",initialize)}jQuery(function($){initialize("'.$detail['latitude'].'","'.$detail['longitude'].'","'.$detail['name'].'")})</script>';
echo '
<div id="container" style="height:500px;width:500px;">
<div id="information">
<h2>'.$detail['name'].'</h2>
<p>'.$detail['description'].'</p>
<p>'.$detail['address'].'</p>
</div>
<div id="map-canvas" style="width:300px;height:200px;">
</div>
</div>
';
Un-minified version of the JS:
function initialize(lat,lng,name) {
lat = parseFloat(lat);
lng = parseFloat(lng);
var ourLocation = new google.maps.LatLng(lat,lng);
var marker;
var map;
var mapOptions = {
center: ourLocation,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
position: ourLocation,
title:name
});
google.maps.event.addDomListener(window,"load",initialize);
};
jQuery(function($){
initialize(lat,lng,name);
// the variables lat, lng, and name are replaced with php variables in the code
});
I figured it out. Took a little while, but...
Wordpress hates the jQuery call for some reason or another.
I noticed that in the JS console, if I called the initialize function with the variables I'd rip from the generated source then the map would magically work.
Instead of using jQuery, I just used the windows onload event.
window.onload = function() { initialize('.$detail['latitude'].','.$detail['longitude'].',"'.$detail['name'].'"); }
Which magically works.
Lesson learned, jQuery and Wordpress are like Strawberry Chocolate Milk and India Pale Ales: they don't mix well.
Thank you everyone that contributed.

Why google map with kml always zoom to the max level?

I made a google map app use google map api v3 and kml file. However, sometime it work, and sometime it always zoom to the max level and center is not mine options.center(near Africa).
Why is it?
And my kml file was uploaded to mine Google Map account.
function initialize1() {
var myLatlng = new google.maps.LatLng(30.566991,114.315491);
var myOptions = {
zoom: 10,
center: myLatlng,
overviewMapControl:true,
overviewMapControlOptions: {
opened:true
},
scaleControl:true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map1= new google.maps.Map(document.getElementById("map_canvas1"), myOptions);
var nyLayer = new google.maps.KmlLayer('https://maps.google.com/maps/ms? **************',
{suppressInfoWindows: true});
nyLayer.setMap(map1);
google.maps.event.addListener(nyLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.description;
showInDiv(text);
});
}
Thanks very much,
That behavior occurs when the kml file doesn't exist/can't be found. You haven't provided the URL of the file to allow testing that.
Another thing to check would be the validity of the file:
http://www.feedvalidator.org/
You could also check the KmlLayerStatus provided by the API to see what it reports.

Google Maps and Location

I'm building an application using CakePHP that will store events including the event location. When a user visits the application they will see a Google Map that will get their location and show events near them in the form of little pins that they can click on to view the event details.
I have some questions though:
1.) How would I store the Location in the DB? Would the actual geolocation coordinates be the best bet and how would I make it easy for a user to create an event and enter them.
2.) Once I have the events in place how do I create custom pins with the info pulled from the DB? Example like foursquare:
3.) Whilst getting the users location using HTML5 Geolocation how do I show a little loader on the map again like Foursquare does?
So far I've managed to create the Map and make the controls minified and get the location of the viewer but I'm not sure how do 3 and show a better feedback to the user for the geolocation.
If someone could help me with those other two questions as well it'd be very much appreciated as I'm finding it very confusing so far. Thanks.
var map;
function initialize() {
var myOptions = {
zoom: 8,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
1) Store the actual coordinates of the location and any extra meta data (if you have it) like place name, foursquare_id, date, etc. Storing it this way will make using the data later on straightforward, such as plotting on a map or location name lookup. This will be your Location model.
Create an Event model which you can then associate to a Location. You could hack together some nice interactive functionality using event handlers on your map markers.
Something like: "the user clicks a location on the map, up pops a box asking them would like like to create a new event at this location, marker is added to the map and a form appears where they can populate the event details, etc, etc." You get the idea.
Have a look at the Marker documentation.
2) You can set a custom image for the map markers using ImageMarker Class. Take a look at the huge set of examples for ideas of what's possible.
3) The navigator.geolocation.getCurrentPosition() method as I understand it, is asynchronous. The first argument is the successCallback.
With this in mind, you could set an overlay on your map: "Finding your location", then make the call to getCurrentPosition(). In your successCallback function, you would then hide the overlay.

When is remove_at event in Google Maps API v3 triggered?

I am working on google map api v3 and want to add a feature of editing the polyline. As of the google documentation. There are 3 events fired when a polyline is in edit mode.
insert_at
set_at
remove_at
I know when first two events are fired and am able to get the edited coordinates as well. I also want to delete a node but not sure how it works?. Can anyone tell me when will the event "remove_at" will be fired ?
According to the documentation these events belong to class google.maps.MVCArray. You can find there also a description of remove_at event:
This event is fired when removeAt() is called. The event passes the
index that was passed to removeAt() and the element that was removed
from the array.
But I'm not sure you can use these events to handle changes while editing the Polyline. That's very interesting, please let us know if it works and how!
'remove_at' will be triggered when you undo an edit to an existing overlay that results in control point(s) getting removed.
I've created a fiddle to demonstrate this.
From the fiddle:
var myLatlng = new google.maps.LatLng(60.629765, 6.424094);
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var drawMan = new google.maps.drawing.DrawingManager({
map: map,
drawingControl: false,
polygonOptions: {
editable: true,
draggable: true
}
});
drawMan.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
google.maps.event.addListener(drawMan, 'overlaycomplete', function (event) {
// When draw mode is set to null you can edit the polygon you just drawed
drawMan.setDrawingMode(null);
google.maps.event.addListener(event.overlay.getPath(), 'remove_at', function () {
alert('remove_at triggered');
});
});

Resources