programing

Google Maps API는 AJAX를 사용할 때만 "Uncatched ReferenceError: google is not defined"를 발생시킵니다.

starjava 2023. 2. 21. 23:17
반응형

Google Maps API는 AJAX를 사용할 때만 "Uncatched ReferenceError: google is not defined"를 발생시킵니다.

Google Maps API를 사용하여 지도를 표시하는 페이지가 있습니다.직접 페이지를 로드하면 지도가 나타납니다.다만, AJAX 를 사용해 페이지를 로드하려고 하면, 다음의 에러가 표시됩니다.

Uncaught ReferenceError: google is not defined

왜 이러한가?

맵이 있는 페이지는 다음과 같습니다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}
$(document).ready(function(e) { initialize() });
</script>
<div id="map_canvas" style="height: 354px; width:713px;"></div>

이 페이지는 AJAX 콜과 함께 표시됩니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(e) {
    $('button').click(function(){
        $.ajax({
            type: 'GET', url: 'map-display',
            success: function(d) { $('#a').html(d); }
        })
    });
});
</script>
<button>Call</button>
<div id="a"></div>
</body>
</html>

도와주셔서 고마워요.

기본적으로 문서 로드가 완료된 후에는 API를 로드할 수 없습니다. 비동기식으로 로드해야 합니다.

맵을 사용하여 페이지를 수정합니다.

<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
    directionsService,
    map;

function initialize() {
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}

</script>

상세한 것에 대하여는, https://stackoverflow.com/questions/14184956/async-google-snot-api-v3-snot-a 함수/14185834#14185834 를 참조해 주세요.

예: http://jsfiddle.net/doktormolle/zJ5em/

이 답변이 이 질문의 문제와 직접 관련된 것은 아니지만, 사용 중인 Google 맵 API보다 먼저 js 파일이 호출되면 "Uncatched ReferenceError: google is not defined" 문제가 발생할 수 있습니다.그러므로 다음 작업을 수행하지 마십시오.

<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

Uncaughed ReferenceError: google is not defined 오류는 맵 API 스크립트태그에서 비동기 지연을 삭제하면 사라집니다.

기능을 초기화하기 전에 다음과 같은 것을 초기화해야 합니다.

var directionsService = new google.maps.DirectionsService();

페이지를 로드하기 전에 실행하려고 하지 않도록 함수로 이동합니다.

var directionsDisplay;
var directionsService;
var map;

function initialize() {
  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
}

당신의 모든 회피책을 따라 한 후 나에게 효과가 있었던 것은 API를 호출하는 것이었습니다.

 <script async defer src="https://maps.googleapis.com/maps/api/js?key=you_API_KEY&callback=initMap&libraries=places"
            type="text/javascript"></script>

를 참조해 주세요.<div id="map"></div>

사용하고 있습니다.ASP NET(MVC)

다른 브라우저를 사용해 봤는데, 스크립트 태그에 이 타입을 넣는 것이 매우 중요하다고 대답했습니다="text/excript"

브라우저 호환성을 위해 모든 js 스크립트에 추가하는 것이 매우 중요합니다.

<script type="text/javascript" src="ANY_FILE_OR_URL"></script>

이 후 다음과 같은 문제가 발생합니다.Uncaught ReferenceError: google is not defined또는 기타(참고문헌을 로드할 수 없는 경우)

수집되지 않은 참조 오류:

구글이 정의되어 있지 않고 구글 관련 정보가 아직 로드되지 않았으며 이 에러의 원인이 되는 것을 사용하고 있습니다.다음의 코드 스니펫에서는, 양쪽의 경우에 에러가 발생하는 것을 알 수 있습니다.initMap 메서드 내에서 구글 관련 정의를 이동하거나 조금 후에 해당 함수를 로드할 수 있습니다.

    //shows the error 
    google.maps.Polygon.prototype.getBounds1 = function (latLng) {
    ...
    };
   function initMap() {
   ...
   //should be here inside the initMap
   }
    //error with the following
    google.maps.Polygon.prototype.getBounds1 = function (latLng) {
        ...
    };

제 경우 위의 솔루션 중 하나가 작동하지 않습니다. 구글 스크립트를 로드하지 않았기 때문입니다.그래서 재귀적으로 확인하는데...구글이 로드했을 때 원래 기능을 호출합니다.

function checkMapLoaded() {
  if (typeof google === "undefined") {
    setTimeout(checkMapLoaded, 1000);
  } else {
    // do some work here
    initSchMap();
  }
}

부분 렌더 함수를 사용하는 경우 동일한 렌더 공간에서 Google 스크립트와 스크립트를 렌더링합니다.

의 마마 my에서는ASP.Net Core.head를 사용합니다.@section head {...}도 ★★★★★★★★★★★★★★★★★★★★★★★★★★★@section head {...}.

두 를 모두 ""에 .@section head{...}을 사용하다

나를 위해.

이 행의 추가

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

이 줄 앞에.

<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>

일했다

Gstatic은 구글이 소유한 도메인이다.CDN 또는 콘텐츠 전송 네트워크에서 Google의 콘텐츠를 빠르게 로드할 수 있도록 지원하는 특별한 역할을 합니다.

행을 에 추가합니다.<HTML></HTML>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 

구글 차트!

언급URL : https://stackoverflow.com/questions/14229695/google-maps-api-throws-uncaught-referenceerror-google-is-not-defined-only-whe

반응형