开发者

Google Maps: "map is not defined"

I'm experimenting with google maps panTo. I have a JQuery application map. and have tried the simple code.

function movemap(latlong) {
    var myLatlng = new google.maps.LatLng(latlong);
   开发者_Go百科 map.panTo(myLatlng);
}

It says map is not Defined in the firebug console. So that means that I have not defined it. So how do I define it.


The problem with the tutorial example is that "map" is a local variable defined and used ONLY inside the initialize() function. If you want to reference it outside that function, which is what you are trying to do, you must define it outside the function. In this case the tutorial should be rewritten like so:

<script type="text/javascript">
  var map;
  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
  }

</script>

Note that "map" is now define outside any function so now any javascript function can reference it.


You might want to go through the tutorial; here's how they've created a new map object:

<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
  }

</script>

where map_canvas is

<div id="map_canvas" style="width:100%; height:100%"></div>


In this line var myLatlng = new google.maps.LatLng(latlong); it looks as if you have two variables running together.

Should it not be var myLatlng = new google.maps.LatLng(lat, long);, with the two variable split by a comma?


The trick is that you need a variable "map" to be global. So instead of initializing it in "initialize function" you simply declare it somewhere in main block,

so instead of this:

function initialize(){
    var mapOptions = {
        center: new google.maps.LatLng(49.6327939,15.4174414),
        zoom: 6,            
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);  
}

you'll do this:

var map;
function initialize(){
    var mapOptions = {
        center: new google.maps.LatLng(49.6327939,15.4174414),
        zoom: 6,            
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), mapOptions);      
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜