Monday, May 20, 2024
129
rated 0 times [  133] [ 4]  / answers: 1 / hits: 131682  / 13 Years ago, sun, october 9, 2011, 12:00:00

I have the following Javascript that includes both the standard Google Maps API initialize() function and custom addMarker() function. The map will load fine however the marker does not get added to the map.



<script type=text/javascript>

// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById(map_canvas), myOptions);
}

// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}

// Testing the addMarker function
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
addMarker(CentralPark);

</script>

More From » google-maps-api-3

 Answers
19

You have added the add marker method call outside the function and that causes it to execute before the initialize method which will be called when google maps script loads and thus the marker is not added because map is not initialized
Do as below....
Create separate method TestMarker and call it from initialize.



<script type=text/javascript>

// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById(map_canvas), myOptions);
TestMarker();
}

// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}

// Testing the addMarker function
function TestMarker() {
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
addMarker(CentralPark);
}
</script>

[#89719] Friday, October 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
matteo

Total Points: 81
Total Questions: 100
Total Answers: 96

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
;