Search code examples
javascriptgoogle-maps-api-3google-maps-api-2geoxml3

KMZ layer not showing when using on a different site


So I have a KMZ layer showing on my website but won't show anywhere else. This is my Javascript:

function getBaseUrl() {
    var e = RegExp(/^.*\//);
    return e.exec(window.location.href);
}

function initialize() {
    function e() {
        navigator.geolocation.getCurrentPosition(function(e) {
            var o = new google.maps.LatLng(e.coords.latitude, e.coords.longitude);
            p ? p.setPosition(o) : p = new google.maps.Marker({
                position: o,
                icon: "http://i.imgur.com/1VTzeOS.png",
                map: map
            }), map.setCenter(t);
        }), setTimeout(e, 3e5);
    }
    var o = new google.maps.LatLng(42.449686, -71.230919), t = o, a = {
        zoom: 12,
        center: o,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), a), geoXml = new geoXML3.parser({
        map: map,
        singleInfoWindow: !0,
        zoom: !1
    }), geoXml.parseKmlString(kmlData);
    for (var n = {
        path: "M 0,-1 0,1",
        strokeOpacity: 1,
        scale: 2.5,
        preserveViewport: !0
    }, i = 0; i < geoXml.docs[0].gpolylines.length; i++) geoXml.docs[0].gpolylines[i].setOptions({
        strokeOpacity: 1,
        strokeWeight: 1,
        zoom: !1,
        icons: [ {
            icon: n,
            offset: "0",
            repeat: "1px"
        } ]
    });
    var r = new google.maps.KmlLayer({
        url: parent + "parking2.kmz",
        strokeWeight: 20,
        strokeOpacity: 0,
        preserveViewport: !0
    });
    r.setMap(map);
    var p = (new google.maps.InfoWindow({
        content: "You are here!"
    }), null);
    e();
}

var parent = getBaseUrl();

google.maps.event.addDomListener(window, "load", initialize);

The parking2.kmz layer will not display on for example 127.0.0.1/localhost with xampp or at http://example.com/test/map.html. It will however show on http://example.com/map.html. Any ideas?


Solution

  • Geoxml3 uses the xmlHttpRequest object to retrieve the KML/KMZ. That is subject to the Same Origin Policy. You can only access KML/KMZ from the exact same domain. Relative URLs should work or you can use a proxy to access data on other domains.

    google.maps.KmlLayer can only display publicly available KML/KMZ (KML/KMZ that Google's servers can access), so won't work with localhost (127.0.0.1/localhost).

    from the documentation:

    KML and GeoRSS Layers : Overview

    The Google Maps JavaScript API supports the KML and GeoRSS data formats for displaying geographic information. These data formats are displayed on a map using a KmlLayer object, whose constructor takes the URL of a publicly accessible KML or GeoRSS file.

    Related: - Is XML subject to the Same Domain Policy in JavaScript when using XMLHttpRequest