programing

Google Maps API v3의 모든 정보 창을 닫습니다.

nasanasas 2020. 11. 13. 08:21
반응형

Google Maps API v3의 모든 정보 창을 닫습니다.


내 웹 사이트에 여러 마커가있는 Google지도 캔버스를 만드는 스크립트로 바쁘다. 마커를 클릭하면 정보 창이 열립니다. 나는 그것을했고 코드는 현재입니다.

 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);
    function addMarker(map, address, title) {
     geocoder = new google.maps.Geocoder();
     geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
     position: results[0].geometry.location,
              map: map,
              title:title
    });
    google.maps.event.addListener(marker, 'click', function() {
     var infowindow = new google.maps.InfoWindow();
            infowindow.setContent('<strong>'+title + '</strong><br />' + address);
             infowindow.open(map, marker);

          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
     });
    }
    addMarker(map, 'Address', 'Title');
 addMarker(map, 'Address', 'Title');

이것은 100 % 작동합니다. 하지만 이제 하나의 정보창이 열려 있고 두 번째 정보창을 열려면 첫 번째 정보창이 자동으로 닫힙니다. 그러나 나는 그것을 할 방법을 찾지 못했습니다. infowindow.close (); 도움이되지 않습니다. 누군가이 문제에 대한 예 또는 해결책이 있습니까?


infowindow는 지역 변수이며 close ()시 창을 사용할 수 없습니다.

var latlng = new google.maps.LatLng(-34.397, 150.644);
var infowindow = null;

...

google.maps.event.addListener(marker, 'click', function() {
    if (infowindow) {
        infowindow.close();
    }
    infowindow = new google.maps.InfoWindow();
    ...
});
...

전역 변수 선언 :

var mapOptions;
var map;
var infowindow;
var marker;
var contentString;
var image;

에서 intialize지도의 사용 addEvent방법

google.maps.event.addListener(map, 'click', function() {
    if (infowindow) {
        infowindow.close();
    }
});

infowindows동적으로 생성되는 루프의 경우 전역 변수 선언

var openwindow;

그런 다음 addListener함수 호출에서 (루프 내에 있음) :

google.maps.event.addListener(marker<?php echo $id; ?>, 'click', function() {
if(openwindow){
    eval(openwindow).close();
}
openwindow="myInfoWindow<?php echo $id; ?>";
myInfoWindow<?php echo $id; ?>.open(map, marker<?php echo $id; ?>);
});

infowindowsCMS에 얼마나 많은 입력이 입력되었는지에 따라 및 마커를 생성하는 동적 루프가 있었기 때문에 InfoWindow()모든 이벤트 클릭에 대해 새로 생성하고 요청이 발생하더라도이를 수렁에 빠뜨리고 싶지 않았습니다 . 대신 infowindow각 인스턴스에 대한 특정 변수가 내가 보유한 위치 수를 벗어나게 될 것인지 확인한 다음 올바른 위치를 열기 전에지도에서 모든 변수를 닫으라는 메시지를 표시했습니다.

내 위치 배열을 위치라고했기 때문에 변수 이름 을 얻기 위해 실제지도 초기화 전에 설정 한 PHP infowindow는 다음과 같습니다.

for($k = 0; $k < count($locations); $k++) {
        $infowindows[] = 'infowindow' . $k; 
} 

그런 다음지도 등을 초기화 한 후 스크립트 foreach에서 카운터를 사용하여 동적 정보 창을 만드는 PHP 루프가 있습니다.

//...javascript map initilization
<?php 
$i=0;
foreach($locations as $location) {

    ..//get latitudes, longitude, image, etc...

echo 'var mapMarker' . $i . ' = new google.maps.Marker({
          position: myLatLng' . $i . ',
          map: map,
          icon: image
      });';

echo 'var contentString' . $i . ' = "<h1>' . $title[$i] . '</h1><h2>' . $address[$i] . '</h2>' . $content[$i] .         '";'; 
echo 'infowindow' . $i . ' = new google.maps.InfoWindow({ ';
echo '    content: contentString' . $i . '
          });';

echo 'google.maps.event.addListener(mapMarker' . $i . ', "click", function() { ';   
    foreach($infowindows as $window) {  
        echo $window . '.close();'; 
    }
        echo 'infowindow' . $i . '.open(map,mapMarker'. $i . ');
      });';

$i++; 
}
?>
...//continue with Maps script... 

요점은 전체 맵 스크립트를 호출하기 전에 InfoWindow()를 만들 때 출력 될 것으로 알고있는 이름의 배열이 있다는 것입니다.infowindow0, infowindow1, infowindow2, etc...

그런 다음 click각 마커 에 대한 이벤트에서 foreach루프가 진행되고 다음 단계를 열기 전에 모든 마커를 닫습니다. 다음과 같이 보입니다.

google.maps.event.addListener(mapMarker0, "click", function() {
    infowindow0.close();
    infowindow1.close();
    infowindow2.close();
    infowindow0.open(map,mapMarker0);
}

내가 생각하는 일을하는 다른 방법이긴하지만 누군가에게 도움이되기를 바랍니다.


다음과 같은 것이 있습니다

function initMap()
{
    //...create new map here
    var infowindow;
    $('.business').each(function(el){
        //...get lat/lng
        var position = new google.maps.LatLng(lat, lng);
        var content = "contents go here";
        var title = "titleText";
        var openWindowFn;
        var closure = function(content, position){.
            openWindowFn = function()
            {
                if (infowindow)
                {
                    infowindow.close();
                }
                infowindow = new google.maps.InfoWindow({
                    position:position,
                    content:content
                });
                infowindow.open(map, marker);
            }
        }(content, position);
        var marker = new google.maps.Marker({
            position:position,
            map:map,
            title:title.
        });
        google.maps.event.addListener(marker, 'click', openWindowFn);
    }
}

In my understanding, using a closure like that allows the capturing of variables and their values at the time of function declaration, rather than relying on global variables. So when openWindowFn is called later, on the first marker for example, the content and position variable have the values they did during the first iteration in the each() function.

I'm not really sure how openWindowFn has infowindow in its scope. I'm also not sure I'm doing things right, but it works, even with multiple maps on one page (each map gets one open infowindow).

If anyone has any insights, please comment.


I encourage you to try goMap jQuery plugin when working with Google Maps. For this kind of situation you can set hideByClick to true when creating markers:

$(function() { 
    $("#map").goMap({ 
        markers: [{  
            latitude: 56.948813, 
            longitude: 24.704004, 
            html: { 
                content: 'Click to marker', 
                popup:true 
            } 
        },{  
            latitude: 54.948813, 
            longitude: 21.704004, 
            html: 'Hello!' 
        }], 
        hideByClick: true 
    }); 
}); 

This is just one example, it has many features to offer like grouping markers and manipulating info windows.


You should have to click your map - $('#map-selector').click();


When dealing with marker clusters this one worked for me.

var infowindow = null;

google.maps.event.addListener(marker, "click", function () {

        if (infowindow) {
            infowindow.close();
        }
        var markerMap = this.getMap();
        infowindow = this.info;
        this.info.open(markerMap, this);


    });

I have been an hour with headache trying to close the infoWindow! My final (and working) option has been closing the infoWindow with a SetTimeout (a few seconds) It's not the best way... but it works easely

    marker.addListener('click', function() {
    infowindow.setContent(html);
    infowindow.open(map, this);

    setTimeout(function(){
        infowindow.close();
    },5000);

});

I have a sample of my code that maybe can help. I had set only one infowindow object at global scope. Then use setContent() to set the content before show it.

  let map;
  let infowindow;
  let dataArr = [
    {
      pos:{lat: -34.397, lng: 150.644},
      content: 'First marker'
    },
    {
      pos:{lat: -34.340, lng: 150.415},
      content: 'Second marker'
    }
  ];

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 8
    });
    // Set infowindow object to global varible
    infowindow = new google.maps.InfoWindow();
    loadMarker();
  }

  function loadMarker(){
    dataArr.forEach((obj, i)=>{
      let marker = new google.maps.Marker({
        position: obj.pos,
        map: map
      });
      marker.addListener('click', function() {
        infowindow.close()
        infowindow.setContent(`<div> ${obj.content} </div>`)
        infowindow.open(map, marker);
      });
    })
  }

참고URL : https://stackoverflow.com/questions/4539905/close-all-infowindows-in-google-maps-api-v3

반응형