Add an onclick event on a marker Google Maps v3 - javascript

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

Related

Scope of google map variables and functions

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

Google Maps Javascript API, how do you draw new markers and center without refreshing the page?

Google Maps Example
I want to add a button to my page that when clicked the map removes the old markers, adds new markers and centers over the last marker added.
For example, call update() and it posts to server and returns new data for map,
function update() {
$.post( '[website]', { post:'map' }, function(data) { if(data) { ??? }});
}
I know there is a way to modify the map by adding internal controls onto the map, but is there a way to basicaly create a new map with new data without reloading the page?
Found it, Listening to DOM events
function initMap() {
var myExternalButton = document.getElementById('myExternalButton');
var map = new google.maps.Map(mapDiv, {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
});
google.maps.event.addDomListener(myExternalButton, 'click', function() {
window.alert('External button was clicked!');
});
}

Google Maps JavaScript - adding multiple markers to one map

I'm having difficulty setting event handlers to Google Maps markers in JavaScript. Below is my code:
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 8,
center: {lat: -35, lng: 149}
});
for (var i = 0; i < basketballCourts.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(basketballCourts[i].latitude, basketballCourts[i].longitude),
map: map,
title: 'Hello World!'
});
marker.set("data-index", i);
google.maps.event.addListener(marker, 'click', function() {
console.log(marker.get("data-index"));
});
}
You'll notice that there is a click event for the markers. However, the click event is the same for all the markers. A different number should be logged for every marker click, but no matter what marker I click on, I get the same response.
I'm not sure how to fix this.
What's happening is you're looping over all your basketballCourts, creating an event listener for each marker. That's all well and good. However that event listener function looks like:
console.log(marker.get("data-index"));
The function executes in response to a marker click, not when you define it. And the value of marker when the function executes will be the value it had at the end of your loop over all the basketballCourts.
Using #MiltoxBeyond's suggestion, try using this.get("data-index")

Google Map with Sidebar that Zooms to a Specific Location

I'm working on a javascript Google map where I have marked the location of each of the state capitals with a custom marker and a title of that capital and state. Right now when you view the map you see the whole US with each marker. I want to keep that but add a sidebar where you click the name of a state and the map zooms to the state and capital. I would also like to add a link that zooms out view the full map. Does anyone have a tutorial on how to do this? I found several examples of Google maps with sidebars but none that zooms to a specific location.
Edit:
This is what I am trying to achieve: http://econym.org.uk/gmap/example_map2.htm
Here is the code I am working with:
<script>
function init() {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(38.781494, -96.064453),
mapTypeId: google.maps.MapTypeId.ROAD
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var image = 'Alabama.png';
var myLatLng = new google.maps.LatLng(32.366805, -86.299969);
var AlabamaMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title:"Montgomery, Alabana"
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
You need to associate listeners (for example, using jquery) with the click event on your state names. Provided they had an id attribute with the USPS code, it would be something like
jQuery(document).on('click','#RESET',function() {
map.setZoom(5);
map.setCenter({lat:41, lng:-89.5});
});
jQuery(document).on('click','#CA',function() {
map.setZoom(7);
map.setCenter({lat:36.4, lng:-120.9});
});
jQuery(document).on('click','#FA',function() {
map.setZoom(7);
map.setCenter({lat:28, lng:-81});
});
You see, I included one link with id RESET that allows me to reset to the initial state.
Here you can see it at work
http://bl.ocks.org/amenadiel/38e0541592bf331cb298

How to get some information in google maps without click event on marker and show this in a div, other than infoWindow

Hi I am showing some markers on my google map and on click of the marker, I am calling the click event and showing some info about that place to the right side(area other than Map and not as an infoWindow). Now this event gets fired on click, and by default when page loads my div remains blank, How can I have the div the basic information being shown up once the map loads up. I need to show the information that corresponds to the marker that is the center point of the map, and later when the users click the marker icons the info should change and correspond to the particular marker being clicked
I have tried something but it doesn't work:
function loadMap() {
var myLatlng = new google.maps.LatLng(40.46998, -3.68705);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var places = [];
places.push(new google.maps.LatLng(51.43581, -0.51744));
places.push(new google.maps.LatLng(48.87187, 2.31764));
places.push(new google.maps.LatLng(45.45979, 9.19681));
var infowindow;
for(var i = 0; i<places.length; i++) {
var marker= new google.maps.Marker({
position: places[i],
map: map,
title: 'Place' + i
});
(function (i,marker){
google.maps.event.addListener(marker, 'click' , function() {
infowindow.setContent('PLace Number' + i)
infowindow.open(i, marker)
});
});(i, marker);
}
}
$("document").ready(function () {
loadMap();
});
UPDATE EDITED
Basically I need something like Layer KML features
But the info should come on the right hand side by default for the first time. Later on when the marker is clicked, the info should change. I am also not adamant that I need this info in a kml file(xml is fine with me as well). I can just have a marker and info should popup on click and for the first time be default as well depending on the location of the user.
Bottom Line: I need the info to appear on click of a marker and by default when the page loads the info should appear corresponding to the center point of the map. which means users coming from different locations will see different info's corresponding to their location from where they are coming.(I am centering the map based on users location)
You can use the addDomListener event of the google maps api. Something like this:
<script>
function initialize() {
// Map initialization
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="map_canvas"></div>
</body>
Although the above code is Maps Javascript API code, the addDomListener() method binds to the window object of the browser and allows the API to communicate with objects outside of the API's normal domain.
further reading
Actually the basic Idea is that you need to read an XMl and parse the data and and show this in a seperate div on right side., This div you can create dynamically when you load the map e-g:
$("#body").append("<div class='newdiv'></div>")
From the google Docs in the section about InfoWindow:
Note that if you call open() without passing a marker, the InfoWindow
will use the position specified upon construction through the
InfoWindow options object.
So in your code, why don't you simply init your infoWindow and call the open() method? I am not particularly familiar with the api, but how about:
var infowindow = new google.maps.InfoWindow({
content: 'your initial text'
});
infowindow.open();
Or if you need the marker for special purposes on the infowindow, init an marker with the center position and use that in the infowindow.open(your_initial_pos) call.
You can use jQuery to .triger() a click event on the first marker on document.ready:
$(marker).trigger('click');
This will run the code you have already written and make it so when the page loads your div will be populated with data from whatever element you trigger the click on.
When you bind to document.ready you don't need encapsulate document in quotes:
$(document).ready(function () {...});
Or you could use the short-hand if you're into that sort of thing:
$(function () {...});
UPDATE
You can place the trigger function call after your for loop where you are setting up the markers:
for(var i = 0; i<places.length; i++) {
var marker= new google.maps.Marker({
position: places[i],
map: map,
title: 'Place' + i
});
(function (i,marker){
google.maps.event.addListener(marker, 'click' , function() {
infowindow.setContent('PLace Number' + i)
infowindow.open(i, marker)
});
});(i, marker);
//only run on the first marker
if (i === 0) {
//trigger a click event to show the first info-window
$(marker).trigger('click');
}
}
You can fire a tilesloaded event on the map object. Check out the Map reference for events
tilesloaded waits until the map tiles are actually loaded before firing. Using your code, you could do something like this:
function loadMap() {
var myLatlng = new google.maps.LatLng(40.46998, -3.68705);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
google.maps.event.addListener(map, 'tilesloaded', function() {
doSomething();
});

Categories