javascript Google Maps API V3 setCenter 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11248344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:32:17  来源:igfitidea点击:

Google Maps API V3 setCenter not working

javascriptgoogle-maps

提问by Cody

I am having issues getting setCenter to work. My JS console tells me:

我在使用 setCenter 时遇到问题。我的 JS 控制台告诉我:

myMap is not defined

myMap.setCenter(newLatLng);

It is clearly defined in the historyMap() function

在historyMap()函数中有明确的定义

My JavaScript

我的 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     });

The HTML calling the setMapCenter function:

调用 setMapCenter 函数的 HTML:

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

I really appreciate any insight anybody can provide.

我非常感谢任何人可以提供的任何见解。

回答by Elorfin

It's because your variable myMapis a local variable : it is only defined for your function historyMap().

这是因为你的变量myMap是一个局部变量:它只为你的函数 historyMap() 定义。

Initialize it, out your functions :

初始化它,出你的功能:

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