UFO ET IT

Google Maps API가로드되었는지 확인하는 방법은 무엇입니까?

ufoet 2020. 12. 28. 21:44
반응형

Google Maps API가로드되었는지 확인하는 방법은 무엇입니까?


Google Maps API (v3)가로드되었는지 확인하는 방법은 무엇입니까?

인터넷 연결 문제 (웹 페이지가 로컬로 호스팅 됨)로 인해 API가로드되지 않은 경우 매핑 스크립트를 실행하고 싶지 않습니다.


if (google.maps) {...} google이 정의되지 않은 경우 (즉, API가로드되지 않은 경우) 참조 오류가 발생합니다.

대신 if (typeof google === 'object' && typeof google.maps === 'object') {...}성공적으로로드되었는지 확인하는 데 사용 하십시오.


현재 답변 중 어느 것도 나를 위해 100 % 일관성으로 작동하지 않습니다 (Google 로더 제외, 시도하지 않았 음). google.maps라이브러리의 로딩이 완료되었는지 확인하는 것만으로는 충분 하지 않다고 생각합니다 . 다음은 Maps API 및 선택적 Places 라이브러리가 요청 될 때 표시되는 네트워크 요청입니다.

API 네트워크 요청 매핑

이 첫 번째 스크립트는를 정의 google.maps하지만 다른 스크립트 중 일부가로드 될 때까지 필요한 코드 ( google.maps.Map, google.maps.places)는 주변에 없을 것입니다.

Maps API를로드 할 때 콜백을 정의하는 것이 훨씬 안전합니다. @verti의 대답은 거의 정확하지만 여전히 google.maps안전하지 않은 검사에 의존합니다 .

대신 다음을 수행하십시오.

HTML :

<!-- "async" and "defer" are optional, but help the page load faster. -->
<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=mapsCallback">
</script>

JS :

var isMapsApiLoaded = false;
window.mapsCallback = function () {
  isMapsApiLoaded = true;
  // initialize map, etc.
};

비동기 로딩에서 이것은 나를 위해 작동합니다 (DaveS에게 감사드립니다) :

   function appendBootstrap() {
    if (typeof google === 'object' && typeof google.maps === 'object') {
        handleApiReady();
    } else {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=handleApiReady";
        document.body.appendChild(script);
    }
}

function handleApiReady() {
    var myLatlng = new google.maps.LatLng(39.51728, 34.765211);
    var myOptions = {
      zoom: 6,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

Google 로더 사용을 고려할 수 있습니다.

google.load("maps", "3", {callback: myFn});

지정된 자바 스크립트 파일을로드 한 다음 optionalSettings인수에 지정된 콜백을 실행합니다 .


편집 : "명시 적이 지 않은"것을 두려워하지 않는 경우 다음을 사용할 수 있습니다. 그렇지 않으면 google변수 인스턴스가 하나만 있는지 확실하지 않은 경우 DaveS 응답을 사용합니다.

Google지도 v3 API가로드되었는지 확인합니다.

if(google && google.maps){
    console.log('Google maps loaded');
}

이 조건 변수에서 google자바 스크립트 진리를 사용하므로 함수 나 객체 또는 문자열이면 true가되고 maps해당 객체 내부에 액세스하려고 시도 합니다.

그리고 역 :

if(!google || !google.maps){
    console.log('Not loaded yet');
}

아시다시피, 수락 된 답변에 문제가 있습니다. 스크립트가로드 된 경우 true를 반환합니다. 그렇지 않으면 'typeof google'이 undefined를 반환하고 오류가 발생할 수 있습니다. 이에 대한 해결책은 다음과 같습니다.

if ('google' in window && typeof google === 'object' && typeof google.maps === 'object') {...}

이렇게하면 부울 값이 항상 반환됩니다.


간단한 if(google && google.maps)수표는 저에게 효과가 없었습니다. API에 액세스하려고하면 여전히 오류가 발생합니다.

TypeError : google.maps.LatLng는 생성자가 아닙니다.

In my case this is probably due to my mouse event handlers being triggered before the maps API has even finished downloading. In this case, to reliably check if maps is loaded, I create a "gmaps" alias and initialise it on dom ready (using JQuery):

var gmaps;
$(function () {
    gmaps = google.maps;
});

then in my event handlers I can simply use:

if(gmaps) {
    // do stuff with maps
}

try

(google && 'maps' in google)?true:false

or

if(google && 'maps' in google){
    //true
}
else{
    //false
}

since I had a problem with the following on mobile:

if (typeof google === 'object' && typeof google.maps === 'object') {...}

I believe you can do this with an if(google && google.maps){ … }, unless you mean what is in this post, which is about Maps API V2, but someone updated it for v3 here.


If you are using jQuery, I have good news for you:

if (typeof google === 'object' && typeof google.maps === 'object') {
     gmapInit();
} else {
     $.getScript('https://maps.googleapis.com/maps/api/js?key='+gApiKey+'&language=en', function(){
         gmapInit();
     });
 }

it's similar to answer-17702802

ReferenceURL : https://stackoverflow.com/questions/9228958/how-to-check-if-google-maps-api-is-loaded

반응형