source

Ajax를 사용하여 Google 지도 v3를 동적으로 로드합니다.

myloves 2023. 9. 5. 21:47

Ajax를 사용하여 Google 지도 v3를 동적으로 로드합니다.

Google 지도 v3를 Ajax와 함께 로드하려고 하면 다음과 같은 결과가 나타납니다.

<script src="http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/8a/main.js" type="text/javascript"></script>

소스 코드에서, 나는 그것이 자바스크립트 문서로 쓴다고 생각합니다.write();

iframe 없이 어떻게 이것을 할 수 있습니까?

감사해요.

실용적인 방법을 찾았습니다.

사용자 지정 이벤트(jQuery):http://jsfiddle.net/fZqqW/94/

window.gMapsCallback = function(){
    $(window).trigger('gMapsLoaded');
}

$(document).ready((function(){
    function initialize(){
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(47.3239, 5.0428),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
    }
    function loadGoogleMaps(){
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type","text/javascript");
        script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    }
    $(window).bind('gMapsLoaded', initialize);
    loadGoogleMaps();
})());​

편집:loadGoogleMaps함수는 특히 Ajax 응용 프로그램에서 작업할 때 글로벌 범위에서 선언된 경우 더 실용적일 수 있습니다.그리고 부울 체크는 내비게이션 때문에 api를 여러 번 로드하지 못하게 할 것입니다.

var gMapsLoaded = false;
window.gMapsCallback = function(){
    gMapsLoaded = true;
    $(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function(){
    if(gMapsLoaded) return window.gMapsCallback();
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}

$(document).ready(function(){
    function initialize(){
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(47.3239, 5.0428),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
    }
    $(window).bind('gMapsLoaded', initialize);
    window.loadGoogleMaps();
});

지원되지 않습니다.지원되는 방법을 사용하여 API를 로드하십시오.

http://code.google.com/apis/maps/documentation/javascript/tutorial.html#Loading_the_Maps_API

난 그렇게 해왔어요.이 예제에서는 jQuery 및 Google 맵 v3.x를 사용합니다.

$.getScript("http://maps.google.com/maps/api/js?sensor=true&region=nz&async=2&callback=MapApiLoaded", function () {});

function MapApiLoaded() {
   //.... put your map setup code here: new google.maps.Map(...) etc
}

ajax로 로드하려면 Google maps API 스크립트에서 'callback=initialize' 매개 변수를 사용해야 합니다.

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>

다음은 Google 지도 설명서입니다.

Como Cargarel API 데포르마 asyncrona

간단한 작동 솔루션(jQuery 사용):

var gMapsLoaded = false;

function loadGoogleMaps() { if(!gMapsLoaded) { $.getScript("https://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=GoogleMapsLoaded", function(){}); } else { GoogleMapsLoaded(); } }

function GoogleMapsLoaded() {

   gMapsLoaded = true;

   // your code here - init map ...
}

이것을 스크립트에 붙여넣은 다음 함수 loadGoogleMaps(); 필요할 때 호출합니다!

나는 미스테리 샘플을 조금 바꿨습니다, 그것은 나에게 잘 맞는 것 같습니다.

    window.mapapiloaded = function () {
        console.log('$.ajax done: use google.maps');
        createusinggmaps();
    };

    $.ajax({
        url: 'http://maps.google.com/-maps/api/js?v=3.2&sensor=true&region=it&async=2&callback=mapapiloaded',
        dataType: 'script',
        timeout: 30000, 
        success: function () {
            console.log('$.ajax progress: waiting for mapapiloaded callback');
        },
        error: function () {
            console.log('$.ajax fail: use osm instead of google.maps');
            createusingosm();
        }
    });
$LAB
  .setOptions({AlwaysPreserveOrder:true})
  .script("http://maps.google.com/maps/api/js?v=3.exp&sensor=false&async=2")
  .script("http://maps.gstatic.com/intl/en_us/mapfiles/api-3/13/6/main.js")
  .script("script.js");

script.js 내부에서는 다음과 같이 Google 로드 방법 없이 지도를 초기화합니다.

Namespace.map = (function(){

    var map,
        markers = [];

    return{
        init: function(){
                var myLatlng = new google.maps.LatLng(-25.363882,131.044922),

                    mapOptions = {
                      zoom: 4,
                      center: myLatlng,
                      mapTypeId: google.maps.MapTypeId.ROADMAP
                    };

                map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: 'Hello World!'
                });

                markers.push(marker);
            }
    };

}());

script.js 내부:

Namespace.map.init();

// Don't use: google.maps.event.addDomListener(window, 'load', initialize);

참고: Google이 두 번째 js 파일의 이름을 변경할 때 이 방법을 사용하지 마십시오.다음은 해당 문서의 예입니다.

https://developers.google.com/maps/documentation/javascript/examples/map-simple-async

이제 가능합니다.여기를 참조하십시오. 이 페이지에는 라이브러리 없이 수동 로드를 위한 변형도 있습니다.

npm install @googlemaps/js-api-loader


import { Loader } from "@googlemaps/js-api-loader"


const loader = new Loader({
apiKey: "YOUR_API_KEY",
version: "weekly",
...additionalOptions,
});

loader.load().then(() => {
 map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
 center: { lat: -34.397, lng: 150.644 },
 zoom: 8,
  });
});

언급URL : https://stackoverflow.com/questions/3922764/load-google-maps-v3-dynamically-with-ajax