Nice programing

Google Maps API v3 : InfoWindow의 크기가 올바르게 조정되지 않음

nicepro 2020. 10. 4. 13:24
반응형

Google Maps API v3 : InfoWindow의 크기가 올바르게 조정되지 않음


내 Google Maps v3에서 홈 아이콘을 클릭하면 내 InfoWindow가 InfoWindow의 콘텐츠에 맞게 크기가 제대로 자동 조정되지 않는 것 같습니다.

안될 때 스크롤바를 제공합니다. InfoWindow는 적절하게 자동 크기 조정되어야합니다.

이유에 대한 아이디어가 있습니까?

요청에 따라 InfoWindow에 HTML을 삽입하는 관련 JavaScript :

listing = '<div>Content goes here</div>';

최신 정보

이 버그는 문제의 Google에서 처리했습니다.

https://issuetracker.google.com/issues/35823659

이 수정 사항은 2015 년 2 월 Maps JavaScript API 버전 3.19에서 구현되었습니다.


정보창에 div 추가

<div id=\"mydiv\">YourContent</div>

그런 다음 css를 사용하여 크기를 설정합니다. 나를 위해 작동합니다. 이것은 모든 정보창의 크기가 같다고 가정합니다!

#mydiv{
width:500px;
height:100px;
}

간단한 대답 : 생성자에서 maxWidth 옵션 속성을 설정합니다 . 예, 최대 너비 설정이 원하는 것이 아니더라도 가능합니다.

더 긴 이야기 : v2 맵을 v3로 마이그레이션하면서 설명 된 문제를 정확히 확인했습니다. Windows는 너비와 높이가 다양했으며 일부는 세로 스크롤바가 있고 일부는 그렇지 않았습니다. 일부는 <br /> 데이터에 삽입되었지만 적어도 그 크기는 괜찮은 것입니다.

너비 제한 하지 않았기 때문에 InfoWindowsOptions.maxWidth 속성이 관련성이 있다고 생각하지 않았습니다 ...하지만 InfoWindow 생성자로 설정하여 원하는 것을 얻었고 이제 창 크기가 (수직으로) 자동 조정되고 세로 스크롤바없이 전체 콘텐츠를 표시합니다. 나에게 많은 의미가 없지만 작동합니다!

참조 : http://fortboise.org/maps/sailing-spots.html


jQuery 객체에서 InfoWindow에 콘텐츠를 제공해야합니다.

var $infoWindowContent = $("<div class='infowin-content'>Content goes here</div>");
var infoWindow = new google.maps.InfoWindow();
infowindow.setContent($infoWindowContent[0]);

.gm-style-iw{
    height: 100% !important;
    overflow: hidden !important;
}

그것은 나를 위해 작동합니다


편집 됨 (눈에 띄기 위해) :이 질문에 대한 수백 개의 다른 답변 중 이것이 왜 발생하는지 설명하는 유일한 올바른 답변입니다.

좋아, 그래서 나는이 스레드가 오래되었고 수천 개의 답변이 있음을 알고 있지만 그중 어느 것도 정답 이 없으며 정답을 게시해야 할 필요성을 느낍니다.

첫째, 스크롤바없이 infoWindow를 표시하기 위해 또는 아무것도 지정 하지 않아도됩니다. 가끔 이렇게하면 실수로 작동하게 될 수 있지만 결국 실패하게됩니다.width'sheight's

둘째, Google Maps API 에는 스크롤링 버그 infoWindow's 가 없으며 작동 방식에 대한 올바른 정보를 찾기가 매우 어렵습니다. 음, 여기 있습니다 :

다음과 같이 infoWindow에서 열리도록 Google Maps API에 지시 할 때 :

var infoWindow = new google.maps.InfoWindow({...});
....
infoWindow.setContent('<h1>Hello!</h1><p>And welcome to my infoWindow!</p>');
infoWindow.open(map);

모든 의도와 목적을 위해 Google지도 div는 페이지 끝에 a 임시로 배치합니다 ( 실제로는 생성 detached DOM tree하지만 div페이지 끝에 존재 한다고 상상하면 개념적으로 이해하기 더 쉽습니다 ). 지정. 그런 다음 div (이 예에서는 내 문서의 CSS 규칙이 적용 h1되고 p태그가 적용됨)를 측정하여 widthheight. 그런 다음 Google은이를 가져 와서 div페이지에 추가되었을 때 얻은 측정 값을 할당하고 지정한 위치의지도에 배치합니다.

많은 사람들에게 문제가 발생하는 곳은 다음과 같습니다. 다음과 같은 HTML이있을 수 있습니다.

<body>
 <div id="map-canvas"><!-- google map goes here --></div>
</body>

그리고 어떤 이유로 든 다음과 같은 CSS :

h1 { font-size: 18px; }
#map-canvas h1 { font-size: 32px; }

문제가 보이십니까? 이 API의 시도가에 대한 측정을 수행 할 때 infoWindow(즉시 표시하기 전에)의 h1내용의 일부의 크기를해야합니다 18px(임시 "측정 사업부는"몸에 추가되기 때문에)하지만, API는 실제로 배치하는 경우 infoWindow에 지도에서 #map-canvas h1선택기가 우선적으로 적용되어 글꼴 크기가 API가의 크기를 측정했을 때 infoWindow와 크게 다르며이 상황에서는 항상 스크롤바가 표시됩니다.

에 스크롤바가있는 특정 이유에 대해 약간 다른 뉘앙스가있을 수 infoWindow있지만 그 이유는 다음과 같습니다.

infoWindow실제 HTML 요소가 마크 업에 표시되는 위치에 관계없이 동일한 CSS 규칙이 내부 콘텐츠에 적용되어야합니다 . 그렇지 않은 경우, 당신은 될 것이다 보장 하여 정보창에 스크롤바를 얻을 수

그래서 제가 항상하는 것은 다음과 같습니다.

infoWindow.setContent('<div class="info-window-content">...your content here...</div>');

내 CSS에서 :

.info-window-content { ... }
.info-window-content h1 { .... }
.info-window-content p { ... }
etc...

따라서 API가 측정 값을 추가하는 위치에 관계없이 div닫기 전 body또는 내부에 #map-canvas적용되는 CSS 규칙은 항상 동일합니다.

RE 편집 : 글꼴 패밀리

Google은 글꼴로드 문제 (아래 설명)에 대해 적극적으로 작업하고있는 것으로 보이며 최근에 기능이 변경되었으므로 infoWindow사용중인 API 버전에 따라 처음 열 때 Roboto 글꼴로드가 표시되거나 표시되지 않을 수 있습니다 . Google이 여전히이 문제에 어려움을 겪고 있음을 보여주는 공개 버그 보고서 ( 변경 로그 에이 버그 보고서가 이미 수정 된 것으로 표시 되었음에도 불구하고 )가 있습니다.

한 가지 더 : 글꼴 가족보기 !!!

API의 최신 화신에서 Google은 영리하게 만들고 CSS 선택기로 타겟팅 할 수있는 것으로 infoWindow 콘텐츠를 래핑하려고했습니다 .gm-style-iw. 위에서 설명한 규칙을 이해하지 못한 사람들에게는 이것이 실제로 도움이되지 않았고 어떤 경우에는 더욱 악화되었습니다. 스크롤바는 거의 항상를 처음 infoWindow열었을 때 나타납니다. 하지만 infoWindow다시 열면 똑같은 내용 으로도 스크롤바가 사라집니다. 진지하게, 전에 혼동하지 않았다면 정신을 잃을 것입니다. 무슨 일이 일어나고 있었는지 :

API가로드 될 때 Google이 페이지에로드하는 스타일을 살펴보면 다음을 볼 수 있습니다.

.gm-style {
     font-family: Roboto,Arial,sans-serif
 ...
}

좋습니다. 그래서 Google은 항상 Robotofont-family를 사용하여지도를 좀 더 일관성있게 만들고 싶었습니다 . 문제는 대부분의 사람들이을 열기 전에 infoWindow브라우저가 아직 Roboto글꼴을 다운로드 하지 않았다는 것입니다 (페이지의 다른 어떤 것도 글꼴을 사용하지 않았기 때문에 브라우저가 다운로드 할 필요가 없다는 것을 알 수있을만큼 똑똑하기 때문입니다) 이 글꼴). 이 글꼴을 다운로드하는 것은 매우 빠르지 만 즉각적인 것은 아닙니다. 를 처음 열면 infoWindowAPI가 콘텐츠 div와 함께 infoWindow를 본문에 추가하여 측정을 수행하면 Roboto글꼴 다운로드가 시작 되지만 다운로드가 완료 infoWindow's되기 전에 측정이 수행되고 창이지도에 배치됩니다 Roboto. 그 결과는 꽤 자주infoWindow콘텐츠가 Arial또는 sans-serif글꼴을 사용하여 렌더링 될 때 측정이 이루어 졌지만지도에 표시되고 Roboto다운로드가 완료 되었을 때 콘텐츠가 다른 크기의 글꼴로 표시되고 있었고, 스크롤바가 처음에 나타납니다. 당신은 infoWindow. 똑같은 파일 infoWindow을 두 번째로 엽니 다. 이 시점에서 Roboto가 다운로드되고 API가 infoWindow콘텐츠를 측정 하고 스크롤바가 표시되지 않을 때 사용됩니다 .


나열된 각 답변을 시도했습니다. 아무도 나를 위해 일하지 않았습니다. 이것은 마침내 영구적으로 수정되었습니다. 내가 상속 한 코드 DIV에는 모든 <h#><p>항목에 래퍼가 있습니다 . 나는 단순히 원하는 최대 너비를 고려하여 동일한 DIV에서 일부 "스타일"을 강제하고 (다른 사람의 수정) 경우에 대비하여 줄 높이 변경을 던졌고 white-space: nowrap, 자동 오버플로가 올바른 조정을 수행하도록했습니다. 스크롤 바, 잘림 및 문제 없음!

html = '<div class="map-overlay" style="max-width: 400px;
                                        line-height: normal;
                                        white-space: nowrap;
                                        overflow: auto;
                                       ">';

이것이 오래된 스레드라는 것을 알고 있지만 동일한 문제가 발생했습니다. InfoWindow에 <h2><p>요소 가 있었고 둘 다 아래쪽 여백이있었습니다. 여백을 제거하고 InfoWindow의 크기가 올바르게 조정되었습니다. 다른 제안 된 수정 사항은 작동하지 않았습니다. InfoWindow 크기 계산이 여백을 고려하지 않는다고 생각합니다.


이것들 중 어느 것도 내 문제를 해결하지 않았기 때문에 내 대답을 목록에 추가하려고합니다. 내 콘텐츠를 div에 래핑하고 해당 div에 클래스를 제공하고 div 에을 min-width지정 maxWidth하고 infoWindow에을 지정하고 둘 다 동일한 크기 여야합니다. 그렇지 않으면 너비 또는 높이가 오버플로됩니다. 내용량이 잘못된 상자에

자바 스크립트 :

// Set up the content for the info box
var content = "<div class='infowindow-content'>" + content + "</div>";

// create a map info box
var infoWindow = new google.maps.InfoWindow({
    maxWidth: 350,
    content: content
});

CSS :

div.infowindow-content {
    min-width: 350px;
}

이 모든 솔루션을 시도했지만 아무것도 작동하지 않았습니다. 시행 착오 끝에 나는 그것을 알아 냈습니다.

<style type="text/css">
#map_canvas {
    line-height:normal;
}
</style>

지도 캔버스 div에 대해 line-height : normal을 설정합니다.


Roboto 웹 폰트에 문제가있는 것 같습니다.

정보창은 제공된 콘텐츠에 따라 인라인 너비 및 높이 속성으로 렌더링됩니다. 그러나 이미 렌더링 /로드 된 웹 폰트로는 계산되지 않습니다. 전체지도가 화면에 인쇄 된 후 글꼴이 렌더링되면 창의 DIV 내부에있는 "overflow : auto"속성으로 인해 스크롤바가 나타납니다.

내가 찾은 해결책은 DIV에 콘텐츠를 래핑 한 다음 CSS를 적용하여 웹 글꼴을 재정의하는 것입니다.

.gmap_infowin {
    font-family: sans-serif !important;
    font-weight: normal !important;
}

<div class="gmap_infowin">Your info window content here.</div>

재미있게도 다음 코드는 WIDTH 스크롤 막대를 수정합니다.

.gm-style-iw
{
    overflow: hidden !important;
    line-height: 1.35;

}

HEIGHT 스크롤 막대를 수정하려면 다음과 같이하십시오.

    .gm-style-iw div
    {
        overflow: hidden !important;
    }

편집 : 공백 추가 : nowrap; 두 스타일 모두 스크롤 막대가 제거 될 때 남아있는 것처럼 보이는 간격 문제를 수정할 수 있습니다. 좋은 지적 네이선.


이것은 나를 위해 작동합니다. 을 넣어 divsetContent

sh_map.infoWindow.setContent([
  '<div id=\"mydiv\">',
  'Your content goes here',
].join(''));

그런 다음이 CSS를 페이지에 추가하십시오.

<style type="text/css">
#map-canvas {
 text-align: center;
 vertical-align: middle;
}
#mydiv {
 font-family: "Comic Sans MS", cursive;
 font-size: 10px;
 border-top-width: 0px;
 border-right-width: 0px;
 border-bottom-width: 0px;
 border-left-width: 0px;
 border-top-style: none;
 border-right-style: none;
 border-bottom-style: none;
 border-left-style: none;
 letter-spacing: normal;
 text-align: center;
 vertical-align: middle;
 word-spacing: normal;
}
</style>

예를 들어 http://www.student-homes-northampton.co.uk를 참조 하십시오 . 집 사진 아래의 링크를 클릭하면 Google지도가 표시됩니다.


이것은 내 문제를 완전히 해결했습니다.

.gm-style-iw {
    overflow: visible !important;
    height: auto !important;
    width: auto !important;
}

IE에서 동일한 문제가 발생하고 이러한 응답에 자세히 설명 된 많은 수정을 시도했지만 IE에서 세로 스크롤바를 안정적으로 제거 할 수 없었습니다.

나에게 가장 잘 맞는 것은 정보창에서 고정 된 글꼴 크기로 전환하는 것이 었습니다- 'px'... 저는 ems를 사용하고있었습니다. 글꼴 크기를 수정함으로써 더 이상 정보창의 너비 나 높이를 명시 적으로 선언 할 필요가 없으며 스크롤바가 사라졌습니다.


지도 컨테이너의 높이도 중요합니다. 작은 경우 infoWindow는 항상 80px 높이입니다. 그렇지 않으면 maxWidth#innerDiv수정 마법처럼 작동합니다.


다른 것이 없으면 창을 연 후 콘텐츠를 추가해보십시오. 이렇게하면 크기가 강제로 조정됩니다.

infoWindow = new google.maps.InfoWindow()
infoWindow.open(map, marker)
infoWindow.setContent(content)

domready 이벤트를 사용하고 정보 창을 다시 열고 domready 이벤트가 두 번 발생한 후 숨겨진 콘텐츠를 표시하여 모든 dom 요소가로드되었는지 확인합니다.

// map is created using google.maps.Map() 
// marker is created using google.maps.Marker()
// set the css for the content div .infowin-content { visibility: hidden; } 

infowindow = new google.maps.InfoWindow();    
infowindow.setContent("<div class='infowin-content'>Content goes here</div>");
infowindow.setPosition(marker.getPosition());
infowindow.set("isdomready", false);
infowindow.open(map);   

// On Dom Ready
google.maps.event.addListener(infowindow, 'domready', function () {
    if (infowindow.get("isdomready")) {
        // show the infowindow by setting css 
        jQuery('.infowin-content').css('visibility', 'visible');               
    }
    else {
        // trigger a domready event again.
        google.maps.event.trigger(infowindow, 'content_changed');
        infowindow.set("isdomready", true);
    }
}

setTimeout (/ * show infowin callback * /, 100)을 시도했지만 콘텐츠 (예 : 이미지)를로드하는 데 너무 오래 걸린 경우에는 작동하지 않는 경우가 있습니다.

Hope this works for you.


I was having the same issue, particularly noticeable when my <h2> element wrapped to a second line.

I applied a class to a <div> in the infoWindow, and changed the fonts to a generic system font (in my case, Helvetica) versus an @font-face web font which it had been using. Issue solved.


//infowindow.setContent(response);    
var infowindowopts = { 
    maxWidth: 274, 
    content: response
};
infowindow.setOptions(infowindowopts);

Add a min-height to your infoWindow class element.

That will resolve the issue if your infoWindows are all the same size.

If not, add this line of jQuery to your click function for the infoWindow:

//remove overflow scrollbars
$('#myDiv').parent().css('overflow','');

I couldnt get it to work in any way shape or form, I was including 3 divs into the box. I wrapped them in an outer div, with widths and heights all set correctly, and nothing worked.

In the end I fixed it by setting the div as absolute top left, and then before the div, I set two images, one 300px wide and 1px high, one 120px high and 1px wide, of a transparent gif.

It scaled properly then!

Its ugly but it works.

You could also do one image and set a zindex I expect, or even just one image if your window has no interaction, but this was containing a form, so, that wasn't an option...


I think that this behavior is because of some css styling in an outer container, I had the same problem but I solved it using an inner div an adding some padding to it, I know it's weird but it solved the problem

<div id="fix_height">
    <h2>Title</h2>
    <p>Something</p>
</div>

And in my style.css

div#fix_height{
    padding: 5px;
}

I had an inline element (an a tag) directly inside of the div with style="overflow:auto"[... wrapped that in a p tag and fixed it.

Looks like any inline element that is not nested in a block element directly inside of the infowindow will cause this.


My answer is to add a listener (using addListenerOnce) to check if the infoWindow has been added to the DOM, then opening the infoWindow again (no need to close it).

// map, marker and infoWindow code, we'll call them 
// myMap, myMarker and myInfoWindow

myInfoWindow.open(myMap, myMarker);
google.maps.event.addListenerOnce(myInfoWindow, 'domready', function(){
                myInfoWindow.open(myMap, myMarker);
            });

Adding the following to my CSS did the trick for me:

white-space: nowrap;

Just to summarize all the solutions that worked for me in all browsers:

  • Don't use margins inside the infowindow, only padding.
  • Set a max-width for the infowindow:

    this.infowindow = new google.maps.InfoWindow({ maxWidth: 200 });

  • Wrap the contents of the infowindow with

    <div style="overflow:hidden;line-height:1.35;min-width:200px;">*CONTENT*</div>

    (change the min-width for the value you set on the infowindow maxWidth)

I have tested it and it worked on every browser, and I had over 400 markers...


I know that lots of other people have found solutions that worked for their particular case, but since none of them worked for my particular case, I thought this might be helpful to someone else.

Some details:

I'm using google maps API v3 on a project where inline CSS is something we really, really want to avoid. My infowindows were working for everything except for IE11, where the width was not calculated correctly. This resulted in div overflows, which triggered scrollbars.

I had to do three things:

  1. Remove all display: inline-block style rules from anything inside of the infowindow content (I replaced with display: block) - I got the idea to try this from a thread (which I can't find anymore) where someone was having the same problem with IE6.

  2. Pass the content as a DOM node instead of as a string. I am using jQuery, so I could do this by replacing: infowindow.setContent(infoWindowDiv.html()); with infowindow.setContent($(infoWindowDiv.html())[0]); This turned out to be easiest for me, but there are lots of other ways to get the same result.

  3. Use the "setMaxWidth" hack - set the MaxWidth option in the constructor - setting the option later doesn't work. If you don't really want a max width, just set it to a very large number.

I don't know why these worked, and I'm not sure if a subset of them would work. I know that none of them work for all of my use cases individually, and that 2 + 3 doesn't work. I didn't have time to test 1 + 2 or 1 + 3.


It wasn't acceptable for me to hard code the width and height of the info window, or to set white-space: nowrap, the maxWidth solution didn't help me and everything else either didn't work or was otherwise inappropriate for my use case.

My solution was to set the content, open the window and then when the domready event is fired, set the height CSS property on the content to whatever the height is, and then force Google Maps to resize the InfoWindow accordingly.

infoWindow is the InfoWindow object, $infoWindowContents is a Jquery object of the contents I want to put in there, map is my Map object. marker is a marker which was clicked.

infoWindow.setContent($infoWindowContents.get(0));

var listener = google.maps.event.addListener(infoWindow, 'domready', function() {
  // Stop listening, otherwise the listeners stack up if the window is opened again
  google.maps.event.removeListener(listener);

  // Set the height on the container to however tall the browser is currently rendering it
  $infoWindowContents.height($infoWindowContents.height());

  // Force Google Maps to recalculate the InfoWindow height
  infoWindow.setContent($infoWindowContents.get(0));
});

infoWindow.open(map, marker);

(I posted the same solution over on a similar question How do I get a google-maps InfoWindow to resize to fit the content that is placed inside of it?)


After losing time and reading for a while, I just wanted something simple, this css worked for my requirements.

.gm-style-iw > div { overflow: hidden !important; }

Also is not an instant solution but starring/commenting on the issue might make them fix it, as they believe it is fixed: http://code.google.com/p/gmaps-api-issues/issues/detail?id=5713


Well this is the one that did the trick for me:

.gm-style-iw>div {
    overflow: visible !important;
}

Only setting overflow: visible on .gm-style-iw actually made the problem worse! I noticed in the Chrome developer tools inspector that there are two divs inside the .gm-style-iw element, both which have overflow: auto set by default.

I'm displaying quite a lot of HTML-formatted text in my InfoWindows, that might be why the other solutions didn't work at all for me.

참고URL : https://stackoverflow.com/questions/1554893/google-maps-api-v3-infowindow-not-sizing-correctly

반응형