移动Google Map Center javascript API [英] Move google map center javascript api

查看:93
本文介绍了移动Google Map Center javascript API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我想将地图的中心移动到新坐标.这是我的地图代码

In my project I want to move the center of the map to new coordinates. This is the code I have for the map

function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(0, 0),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);
  }
  function moveToLocation(lat, lng){
     var center = new google.maps.LatLng(lat, lng);
     var map = document.getElementById("map_canvas");
     map.panTo(center);

  }

moveToLocation函数确实被调用,但地图未居中.知道我想念什么吗?

The moveToLocation function does get called but the map does not re center. Any idea what I'm missing?

推荐答案

您的问题是在moveToLocation中,您正在使用document.getElementById尝试获取Map对象,但这只会为您提供HTMLDivElement,而不是您期望的google.maps.Map元素.因此,变量map没有panTo函数,这就是为什么它不起作用的原因.您需要将map变量放到某个地方,它应该按计划工作.您可以像这样使用全局变量:

Your problem is that in moveToLocation, you're using document.getElementById to try to get the Map object, but that only gets you an HTMLDivElement, not the google.maps.Map element you're expecting. So your variable map has no panTo function, which is why it doesn't work. What you need to is squirrel the map variable away somewhere, and it should work as planned. You can just use a global variable like so:

window.map = undefined;      // global variable

function initialize() {
  const mapOptions = {
    center: new google.maps.LatLng(0, 0),
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  // assigning to global variable:
  window.map = new google.maps.Map(
    document.getElementById("map_canvas"), mapOptions);
}

function moveToLocation(lat, lng){
  const center = new google.maps.LatLng(lat, lng);
  // using global variable:
  window.map.panTo(center);
}

在此处查看有效的jsFiddle: http://jsfiddle.net/fqt7L/1/

See working jsFiddle here: http://jsfiddle.net/fqt7L/1/

这篇关于移动Google Map Center javascript API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆