简体   繁体   中英

How to get center point of KML with Google Maps API

I am trying to get the center latLng point of a KML file and store it in a variable for the map setup, but I keep getting the error "Uncaught TypeError: Cannot read property 'getCenter' of undefined(…)". The getDefautViewport is coming back undefined and I am not sure why. My code so far:

    var map;
    function initMap() {

      map = new google.maps.Map(document.getElementById('map'), {
        center: getCenter,
        zoom: 10
        }
      });

      var layer1 = new google.maps.KmlLayer({
        url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
        preserveViewport: true,
        map: map
      });

      var getCenter = layer1.getDefaultViewport().getCenter();

    } 

If you want the map centered on the KML, set preserveViewport: false , then you don't need to set the center.

You can't retrieve the default viewport of the KmlLayer until it has been added to the map, and you can't add it to the map until the map has been created. Don't set the center property of the map when you create it:

map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10
});

wait for the defaultviewport of the KmlLayer to be available, then set the map center:

google.maps.event.addListener(layer1, 'defaultviewport_changed', function() {
    var getCenter = layer1.getDefaultViewport().getCenter();
    map.setCenter(getCenter);
  });

proof of concept fiddle

code snippet:

 var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 10 }); var layer1 = new google.maps.KmlLayer({ url: 'https://googlearchive.github.io/js-v2-samples/ggeoxml/cta.kml', preserveViewport: true, map: map }); google.maps.event.addListener(layer1, 'defaultviewport_changed', function() { var getCenter = layer1.getDefaultViewport().getCenter(); map.setCenter(getCenter); console.log(getCenter.toUrlValue(6)); }); } google.maps.event.addDomListener(window, "load", initMap);
 html, body, #map { height: 100%; width: 100%; margin: 0px; padding: 0px }
 <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script> <div id="map"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM