2012-06-28 66 views
0

我遇到setCenter工作問題。我的JS控制檯告訴我:Google Maps API V3 setCenter無法正常工作

myMap is not defined 

myMap.setCenter(newLatLng); 

它在historyMap明確定義()函數

我的JavaScript

44  function historyMap() { 
45   var travelCoords = new Array(); 
46   var allCoords = new Array(); 
47   var myOptions = { 
48     center: new google.maps.LatLng(<?php echo $places[$lastPlace]['lat']; ?>, <?php echo $places[$lastPlace]['long']; ?>), 
49     zoom: 8, 
50     mapTypeId: google.maps.MapTypeId.HYBRID 
51   }; 
52   var myMap = new google.maps.Map(document.getElementById("map"), myOptions); 
53   allCoords = [ 
54   <?php for($i = 0; $i < $numPlaces; $i++) { ?> 
55     new google.maps.LatLng(<?php echo $places[$i]['lat']; ?>, <?php echo $places[$i]['long'];?>), 
56   <?php } ?> 
57   ]; 
58   var travelPath = new google.maps.Polyline({ 
59     path: allCoords, 
60     strokeColor: "#FF0000", 
61     strokeOpacity: 1.0, 
62     strokeWeight: 4 
63   }); 
64   lastLatLng = new google.maps.LatLng(<?php echo $places[$lastPlace] ['lat'];?>, <?php echo $places[$lastPlace]['long'];?>); 
65   var marker = new google.maps.Marker({ 
66     icon: 'img/<?php echo $icon; ?>', 
67     position: lastLatLng, 
68     map: myMap, 
69     title: '<?php echo $places[$numPlaces-1]['title'];?>' 
70   }); 
71   travelPath.setMap(myMap); 
72  } 
73 
74  function setMapCenter(lat,lng) { 
75 
76   var newLatLng = new google.maps.LatLng(lat,lng); 
77   myMap.setCenter(newLatLng); 
78 
79  } 
80 
81  $(function() { 
82   historyMap(); 
83  }); 

的HTML調用setMapCenter功能:

<td><a href="javascript:void(0);" onClick="setMapCenter('49.261226','-123.113927')">Vancouver</a></td> 

我真的很感謝任何人都能提供的見解。

回答

1

這是因爲您的變量myMap是一個局部變量:它只爲您的函數historyMap()定義。

初始化它,你的功能:

var myMap = {}; 
function historyMap() { ... } 
// other functions 
+0

謝謝你,well.as附加的註釋工作,我不得不刪除從VAR MYMAP的VAR在historyMap()函數。 – Cody