I am creating a phonegap application for android. I am not really familiar with Javascript and have encountered a scenario where I have two functions, one which initialises a map called “map” and another which takes care of showing a list of markers which is being loaded from a database on the map.
However my question is how am I able to set the marker to appear on a map which is initiated in a different function?
EDIT
Here is some code:
function map() {
...
map = new google.maps.Map(document.getElementById("map"), mapOptions);
...
}
function markers() {
var MarkerType1 = new google.maps.MarkerImage("/android_asset/www/assets/markerType1.png",
new google.maps.Size(29.0, 48.0),
new google.maps.Point(0, 0),
new google.maps.Point(14.0, 24.0)
);
var MarkerType2 = new google.maps.MarkerImage("/android_asset/www/assets/markerType2.png",
new google.maps.Size(29.0, 48.0),
new google.maps.Point(0, 0),
new google.maps.Point(14.0, 24.0)
);
var geocoder = new google.maps.Geocoder();
var eventList = $('ul#eventList').empty();
var eventPoints = $.ajax({
type: 'GET',
url: 'http://www.somedomain.com/loadEvents.php?&jsoncallback=?',
dataType: 'JSONp',
timeout: 5000,
success: function(data) {
$.each(data, function(i,item){
if (item.EventType == 1) {
new google.maps.Marker({
position: new google.maps.LatLng(item.latitude, item.longitude),
map: this.map,
icon: MarkerType1,
draggable:false
});
} else if (item.EventType == 2) {
new google.maps.Marker({
position: new google.maps.LatLng(item.latitude, item.longitude),
map: this.map,
icon: MarkerType2,
draggable:false
});
}
}
}
});
}
This is a question of variable scope. Make sure the variable
mapis declared outside both of the functions.eg. :
In practice, you would only need to put the map/marker creation code inside functions if it needed to be called in response to some future event(s).
If you want to create the map and its markers immediately, when page is loaded, then you can do so as follows :