Get google.maps.Map instance from a HTMLElement

后端 未结 5 662
故里飘歌
故里飘歌 2021-01-31 07:21

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

5条回答
  •  萌比男神i
    2021-01-31 08:05

    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 mapa object, for example:

    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 lng and lat values are different then while calling function that creates a map.

    Hope that helps.

提交回复
热议问题