i\'am a beginner in GMaps API and javascript, so this should be an easy question for you that are really experts. I have started to \"play around\" with the API, and wanted
map
is a local variable to initialise()
- the other functions don't have access to it, so declare it outside of initialise()
. Then have a new function that returns the map's current zoom.
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-35.8190,-61.9010),
zoom: 15,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function getCurentZoom() {
return map.getZoom();
}
function cambiarZOOM(nro) {
var newZ = getCurentZoom() + nro;
map.setZoom(newZ);
}
google.maps.event.addDomListener(window, 'load', initialize);
Your problem is that the cambiarZOOM
function and map
variable are only accessible within the scope of the initialize function. To use a function on an onclick event, either it has to be available globally (this is discouraged), or you have to attach the function to the button while the function is in scope.
If you give your button an id (id='zoomButton'
), you can attach cambiarZOOM
within the initialize function like so:
...
function cambiarZOOM(nro) {
var newZ = ez + nro;
map.setZoom(newZ);
}
}
var button = document.getElementById('zoomButton');
button.onclick = function () { cambiarZOOM(5); };
Your cambiarZOOM function is local to the initialize function (it is contained by that function). It needs to be in the global scope (outside of any function declaration) to be used in an HTML event handler (like "onclick"). Your "map" variable also needs to be global to be used in it.
<script type="text/javascript">
var map = null;
function initialize() {
//CREATE THE MAP
var mapOptions = {
center: new google.maps.LatLng(-35.8190,-61.9010),
zoom: 15,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function cambiarZOOM(nro) {
//GET THE ZOOM
var ez = map.getZoom();
var newZ = ez + nro;
map.setZoom(newZ);
}
</script>