Scope of google map variables and functions - javascript

I'm experimenting with Google maps and am trying to put some polyLines up on the fly. Basically, within the body of the document, I have a setInterval function which will periodically put up lines for a certain time and then erase them after an elapsed duration. The problem comes with accessing the various map variables, but when I try and invoke the test programme (below), I get errors like "marker1 not defined". Is it possible to access the map variables from outside the map initialisation routine?
Here is the Javascript code - this is all within the head
var commsLine = [];
var marker1, marker2, marker3, map, Comms;
function initMap() {
latLng = new google.maps.LatLng(50.8917,-1.3989);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: latLng,
mapTypeId: google.maps.MapTypeId.HYBRID,
scaleControl: true
});
marker1 = new google.maps.Marker({
position: new google.maps.LatLng(50.8917, 0),
map: map
});
marker2 = new google.maps.Marker({
position: new google.maps.LatLng(50.8917, -1.5),
map: map
});
marker3 = new google.maps.Marker({
position: new google.maps.LatLng(51.5, 0),
map: map
});
// DrawLine(); works when placed here but I want to call it from the
// setInterval function in the body
}
function DrawLine()
{
commsLine.push( marker1.getPosition() );
commsLine.push( marker2.getPosition() );
Comms = new google.maps.Polyline({
path: commsLine,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
Comms.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initMap);

I think youve got a race problem:
var marker 1;//var init
drawLine();//draw line called, marker isnt set yet
initMap(); //map ready
Solution 1:
Lock drawLine() until initMap is finished
var mapready=false;
function initMap(){
//your code
mapready=true;
}
function drawLine(){
if(!mapready){return false;}
//your code
}
This is a good solution if drawLine can be caused by the user.
Solution 2a:
call drawLine when the map is inited:
function initMap(){
//your code
drawLine();
}
Solution 2b:
Solution a isnt good if you want to call drawLine dynamically (sometimes,sometimes not).
Than it would be good to register callbacks:
mapready=[];
function initMap(){
//your init code
//map is ready so call callbacks
for(i=0;i<mapready.length;i++){
mapready[i]();
}
//if an callback is added now, fire it directly
mapready={};
mapready.push=function(func){func();};
}
To add a callback:
mapready.push(drawLine);

Related

Add an onclick event on a marker Google Maps v3

Although somehow, there are several questions related to my question, this is why my question is different. Using Phonegap, I have an index.html and gmap.html. On my index.html, my href contains parameters :
example: gmap.html?&name=Agustina%20Apartments&lat=14.625486&lng=121.02333099999998
I was able to parse the parameters and put a marker on the map. However, I want to assign an onclick on the marker. I have this code:
google.maps.event.addListener(marker, 'click', callNumber('84'));
Now, what I am trying to do is when the user clicks on the marker, the accompanied contact_number will be opened on the phones's dialer so the user can call the establishment. I have a code that setups a marker using the coordinates from the url. I tried to put it inside my onSuccess callback of my navigator.geolocation.watchPosition method with timeout of 5 seconds. What happens is every 5 seconds, the dialer will appear with the phone number (because of the timeout). However, when I click on the marker, nothing happens. I tried to put it in my initialize() function, but it showed dialer before showing the map, and the marker not being able to detect click events.
Here is a more detailed code:
function initialize() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(14.6333, 121.0333)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var estabCenter = new google.maps.LatLng(lat,lng);
var estabMarker = new google.maps.Marker({
map: map,
position: estabCenter
});
var estabCircle = new google.maps.Circle({
map: map,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
center: estabCenter
});
estabCircle.setRadius(100);
google.maps.event.addListener(estabMarker, 'click', callNumber('84'));
// Try HTML5 geolocation
if(navigator.geolocation) {
mapAutoUpdate();
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function callNumber(number){
window.open('tel:'+number+'', '_system');
}
Thank you for those who will help me.
Supply a function as callback, not a function-call(except the call returns another function):
google.maps.event.addListener(estabMarker, 'click', function(){callNumber('84');});

Undefined property error when refreshing map

Below is the full code of my Google Maps javascript file. What I'm trying to do is first initialise the map, then dynamically add a marker and refresh the map.
// GLOBALS
var map;
function refreshMap() {
google.maps.event.trigger(map,'resize');
map.setCenter(map.get('originalCenter'));
}
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
scrollwheel: false,
center: new google.maps.LatLng(56.4611388, -2.9719832),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
originalCenter: new google.maps.LatLng(56.4611388, -2.9719832)
}
map = new google.maps.Map(map_canvas, map_options)
}
// Initialise Map
google.maps.event.addDomListener(window, 'load', initialize);
// Add a Marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(56.4611388, -2.9719832),
map: map,
title: 'Marker'
});
// Refresh
refreshMap();
I'm getting the following error when refreshMap() is run:
Uncaught TypeError: Cannot read property '__e3_' of undefined main.js:15
Is this the correct way to refresh the map?
The way your code currently runs is it sets up the initialize function to run when the page load event fires, then creates a marker (map is not yet initialized as the page load event has not fired), then calls refreshMap (again before the page load event so the map is still not initialized). The code below triggers the refreshMap function when the button is clicked, but it can't be run until the page is loaded and the initialize function has run.
working fiddle
// GLOBALS
var map;
function refreshMap() {
google.maps.event.trigger(map, 'resize');
map.setCenter(map.get('originalCenter'));
}
// this function runs on the page load event after the DOM has been rendered
// and both the map_canvas and btn elements exist.
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
scrollwheel: false,
center: new google.maps.LatLng(56.4611388, -2.9719832),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
originalCenter: new google.maps.LatLng(56.4611388, -2.9719832)
};
map = new google.maps.Map(map_canvas, map_options);
// need do do this in the initialize function, after the page has loaded and the 'btn' exists
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function () {
// Add a Marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(56.4611388, -2.9719832),
map: map,
title: 'Marker'
});
// Refresh
refreshMap();
});
}
// Initialize Map
google.maps.event.addDomListener(window, 'load', initialize);

Markers not showing on google maps

I'm trying to show markers on my map. but it's not showing them.
this is the code I use:
var map;
var markers = new Array();
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(27.9881, 86.9253),
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addListener(map, 'click', addMarker);
}
function addMarker(event) {
markers.push(event.latLng);
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
console.log(markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
the console is logging on every click an new coordinate, so the function is called, and coordinates are passed. And I can't really see any problems in the marker code.
So can anyone see the problem?
map is a local variable, only visible inside initialize.
Use this instead of map when you set the map-property of the marker:
function addMarker(event) {
markers.push(event.latLng);
marker = new google.maps.Marker({
position: event.latLng,
map: this
});
}
Explanation:
the callback will be executed in the scope of the object that triggers the event. Here it is the Maps-instance(because the click-listener has been applied to the map ), this will refer to this object inside the callback.
markers.push(event.latLng);
Here you're pushing the latlng, not the marker.
markers is an array variable with global scope, whereas marker is a local variable.
In markers array you have to insert each inidividual marker and then process it.
function addMarker(event) {
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
markers.push(marker);
}

Showing additional marker in google map through ajax

I have created a google map using "maps.googleapis.com/maps/api/js?v=3". In that map I am showing markers for different locations, which is working fine. Below is the code which i have used.
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map1'), {
zoom: 10,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(23.42323, -45.47653),
});
});
Now I want to add some more location markers in Ajax. For ex: I will add the location name from a dropdown, it will do an ajax call to the server side. Pull out the location latitude and longitude and will show in the map. How can i achieve it.
I have written a separate js function to do the ajax call, but inside that the code is not getting 'map' instance.Here I have used only this code
new google.maps.Marker({
map: map,
position: new google.maps.LatLng(23.42323, -45.47653),
});
Here I am not initializing the map again. So its not getting the map instance and throwing error. How to fix it.
The scope of your map is limited to inside your event handle. Try this:
var map, markerCollection;
google.maps.event.addDomListener(window, 'load', function() {
map = new google.maps.Map(document.getElementById('map1'), {
zoom: 10,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
function addMarker(lat, lng){
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
});
markerCollection.push(marker);
}
NOTES:
1) Be to fill in the values for "latitude" and "longitude" when defining the center of your map. Otherwise you just would get a map displayed.
2) I know it might not be the best practice to add your markers into an array but I find this makes than easy to access latter.
Since map is not a global variable it is getting dereferenced. Make the map object either global or within a container function that stores all of your code.
Global JS example
//now it's global
var map;
google.maps.event.addDomListener(window, 'load', function () {
map = new google.maps.Map(document.getElementById('map1'), {
zoom: 10,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(23.42323, -45.47653),
});
});

Using 2 methods to display markers and polylines on a Google map

I am trying to combine two separate methods to display both markers and polylines on one map. Is it possible? and if so how would I do this. Or conversely how would I add polylines to my markers sample.
From http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/
Without my actual code I appreciate this is a probably a wasted post.. but I am having trouble adding my code..
Perhaps that should have been my first question..
This script will add markers and draw a polyline between them:
<script>
var poly;
var map;
function initialize() {
var chicago = new google.maps.LatLng(41.879535, -87.624333);
var mapOptions = {
zoom: 7,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addLatLng);
}
/**
* Handles click events on a map, and adds a new point to the Polyline.
* #param {MouseEvent} mouseEvent
*/
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
</script>
Excellent Documentation available here:
https://developers.google.com/maps/documentation/javascript/reference
https://google-developers.appspot.com/maps/documentation/javascript/examples/polyline-complex
It is certainly possible to display markers and polylines on the same map:
Here is an example that displays both markers and independent polylines.
Here is an example that uses the third party geoxml3 KML parser to create them from a KML file (or using KmlLayer).

Categories