Javascript 从 HTMLElement 获取 google.maps.Map 实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10253265/
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-08-24 00:29:54  来源:igfitidea点击:

Get google.maps.Map instance from a HTMLElement

javascriptgoogle-mapsgoogle-maps-api-3

提问by Olly Hicks

I have an existing map on a page. I can select that element using something along the lines of document.getElementById() to get the HTMLElement javascript object. Is it possible to get the instance of google.maps.Map created when the map is initialised, i.e. is it a property of the HTMLElement object or in its prototype?

我在页面上有一个现有的地图。我可以使用类似 document.getElementById() 的方法选择该元素来获取 HTMLElement javascript 对象。是否可以获得在地图初始化时创建的 google.maps.Map 实例,即它是 HTMLElement 对象的属性还是在其原型中?

回答by Engineer

You can't get google.maps.Mapobject from DOM Element,on which Google Maps object have been constructed. google.maps.Mapis just a wrapper, which controls DOM Elementfor viewing the map, and that element does not have reference to its wrapper.

您无法从中获取google.maps.Map对象DOM Element,在其上构建了 Google Maps 对象。google.maps.Map只是一个包装器,用于控制DOM Element查看地图,并且该元素没有对其包装器的引用。

If your problem is only the scope, make mapas a property of windowobject, and it will be accessible from everywhere in your page. You can make 'map'as global by using one of these:

如果您的问题只是范围,请将 makemap作为window对象的属性,并且可以从页面中的任何位置访问它。您可以'map'使用以下方法之一使其成为全球性的:

 window.map = new google.maps.Map(..) 

or

或者

 map = new google.maps.Map(...) //AVOID 'var' 

回答by goldsky

You can get google.maps.Mapobject from DOM Element, with a slight trick.

您可以通过一个小技巧google.maps.Map从中获取对象DOM Element

When you initialize map object, you need to store the object on element's data attribute.

初始化地图对象时,需要将该对象存储在元素的数据属性上。

Example:

例子:

$.fn.googleMap = function (options) {
    var _this = this;

    var settings = $.extend({}, {
        zoom: 5,
        centerLat: 0,
        centerLon: 0
    }, options);

    this.initialize = function () {
        var mapOptions = {
            zoom: settings.zoom
        };

        var map = new google.maps.Map(_this.get(0), mapOptions);
        // do anything with your map object here,
        // eg: centering map, adding markers' events

        /********************************************
         * This is the trick!
         * set map object to element's data attribute
         ********************************************/
        _this.data('map', map);

        return _this;
    };
    // ... more methods

    return this;
};

After you define a map element, eg:

定义地图元素后,例如:

var mapCanvas = $('#map-canvas');
var map = mapCanvas.googleMap({
    zoom: 5,
    centerLat: 0,
    centerLong: 0
});
// ... add some pre-load initiation here, eg: add some markers
// then initialize map
map.initialize();

you can then get the map object later on by using element's ID, eg:

然后您可以稍后使用元素的 ID 获取地图对象,例如:

var mapCanvas = $('#map-canvas');
$('.location').on('click', function () {
    // google map takes time to load, so it's better to get
    // the data after map is rendered completely
    var map = mapCanvas.data("map");
    if (map) {
        map.panTo(new google.maps.LatLng(
            $(this).data('latitude'),
            $(this).data('longitude')
            ));
    }
});

By using this method, you can have multiple maps with different behaviors on a page.

通过使用此方法,您可以在一个页面上拥有多个具有不同行为的地图。

回答by ThePueblo

I had a similar problem. All I wanted to do was to manipulate maps after they where created. I tried something like that (I think it will help you too). I've created function (more or less like this):

我有一个类似的问题。我想做的就是在创建地图后对其进行操作。我试过类似的东西(我认为它也会帮助你)。我已经创建了函数(或多或少像这样):

function load_map(el_id, lat, lng) {
  var point = new google.maps.LatLng(lat,lng);
  var myMapOptions = {
    scrollwheel:false,
    zoom: 15,
    center: point,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
      position: google.maps.ControlPosition.RIGHT_TOP
    },
    navigationControl: true,
    navigationControlOptions: {
      style: google.maps.NavigationControlStyle.SMALL,
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById(el_id),myMapOptions);
  var marker = new google.maps.Marker({
    draggable:true,
    map: map,
    position: point
  });
  return({
    container:map.getDiv(),
    marker:marker,
    mapa:map
  });
}

What this function does is after calling it to create a map in some container.

该函数的作用是在调用它以在某个容器中创建地图之后。

var mapa = load_map('mapa_container', 53.779845, 20.485712);

Function will return object containing some data used while making the map. After creating a map itself I can simply manipulate, in my case, marker on each map separately using mapaobject, for example:

函数将返回包含制作地图时使用的一些数据的对象。创建地图本身后,我可以简单地操作,在我的情况下,使用mapa对象分别在每个地图上进行标记,例如:

mapa.marker.setPosition(new google.maps.LatLng(20,30));
mapa.mapa.setCenter(new google.maps.LatLng(20,30));

This will change marker position and center map to the same coords. Notice that lngand latvalues are different then while calling function that creates a map.

这会将标记位置和中心地图更改为相同的坐标。请注意,在调用创建映射的函数时,lnglat值是不同的。

Hope that helps.

希望有帮助。

回答by keune

You create an instance when you initialize a map;

在初始化地图时创建一个实例;

var map = new google.maps.Map(document.getElementById("map_element"), options);

You use that instance whenever you want to do something like putting a marker, changing location, etc. It's not an HTMLElement object. However it has a getDiv()method, which gives you the html element it's operating on.

每当您想要执行诸如放置标记、更改位置等操作时,都可以使用该实例。它不是 HTMLElement 对象。但是它有一个getDiv()方法,可以为您提供它正在操作的 html 元素。

map.getDiv(); // in this case it returns the element with the id 'map_element'

回答by Naveed Ul Islam

If you are using Google-map component from the Polymer project, you can get the existing map Dom like this:

如果您使用 Polymer 项目中的 Google-map 组件,您可以像这样获取现有的地图 Dom:

var map = document.querySelector('google-map');

Once you have that, current instance of map can be accessed by:

一旦有了它,就可以通过以下方式访问地图的当前实例:

var currentMapInstance = map.map;