How to get Google Maps API to set the correct zoom level for a country?

后端 未结 4 624
长情又很酷
长情又很酷 2020-11-28 02:30

Is there a was of automatically setting the zoom level based on the size of the country that the map has been centered on?

maps.google.com does exactly what I need,

4条回答
  •  一向
    一向 (楼主)
    2020-11-28 03:09

    If you don't want to use the geocoder client from google, because of usage limitations you could use your own list. You can get one from this github repo.

    Here is a code example using jQuery's getJSON function and google maps API v3:

        function initialize() {
          // read the list of countries
         $.getJSON('countries.json', function (countries) {
    
             // will use the country with index 40 (Cyprus)
             var index_country = 40;
             var myOptions = {
                 center: new google.maps.LatLng(
                     countries[index_country].center_lat,
                     countries[index_country].center_lng),
             }
             var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
             // set the bounds of the map
             var bounds = new google.maps.LatLngBounds(
                 new google.maps.LatLng(countries[index_country].sw_lat, countries[index_country].sw_lng),
                 new google.maps.LatLng(countries[index_country].ne_lat, countries[index_country].ne_lng) );
    
             map.fitBounds(bounds);
         });
     }
    

提交回复
热议问题