Reputation: 7798
How can I add new marker to the map? I managed to show the map function startGoogleMaps()
but my function (onclick()
), does not work.
function startGoogleMaps(){
var map = new google.maps.Map(document.getElementById('canvasMap'), {
zoom: 5,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: (37, -97),
map: map,
title:"Hello World!"});
}
Upvotes: 0
Views: 373
Reputation: 15399
Keep in mind that Javascript uses functional scope. You'll need to declare map
globally like so:
var map;
function startGoogleMaps(){
map = new google.maps.Map(document.getElementById('canvasMap'), {
zoom: 5,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37, -97),
map: map,
title:"Hello World!"});
}
In addition, the marker itself may be outside the scope of your map, so you can use map.fitBounds
to display it properly:
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37, -97),
map: map,
title:"Hello World!"});
var latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend(new google.maps.LatLng(37, -97));
map.fitBounds(latlngbounds);
}
Upvotes: 1
Reputation: 30531
Try defining the map
object in the same scope as you are binding the click event:
var map = null;
function startGoogleMaps(){
map = new google.maps.Map(document.getElementById('canvasMap'), {
zoom: 5,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: (37, -97),
map: map,
title:"Hello World!"});
}
Also note that you need to pass your position as an instance of google.maps.LatLng
:
...
position: google.maps.LatLng(37, -97),
...
Upvotes: 2