如何检查/了解多个国家/地区是否在Google地图API中显示在当前视口中

时间:2016-03-08 08:58:50

标签: jquery google-maps google-maps-api-3

我使用了map.getBounds().contains(point)containsLocation()方法。它告诉我们视口中是否存在点,但是我无法弄清楚如何找出视口中有多个国家/州,并且.contains(point)containsLocation()检查一点。我要检查数百或数千个积分吗?不会。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我建议在服务器端收集这些数据,在客户端,您需要加载所需区域的所有边界(数百万个点),使用脚本语言迭代它们需要很长时间。

您需要什么:支持空间查询的数据库(例如Postgres with PostGIS,MySQL V5.6 +,Google FusionTables)。

这些数据库支持函数ST_INTERSECTS,它检查给定的列是否与几何相交(例如,RECTANGLE ......在本例中是地图的视口)。

使用FusionTables / jQuery的示例实现可能如下所示:

    var map             = /*google maps instance*/,
        //ID of the FusionTable(table must be downloadable)
        tableId         = '1N2LBk4JHwWpOY4d9fobIn27lfnZ5MDy-NoqqRpk',
        //your API-key(FusionTablesAPI must be enabled for the project)
        apiKey          = 'yourApiKey',
        //name of the column where the boundaries are stored
        locationColumn  = 'geometry',
        //names of the columns you like to receive
        columns         = ['Name'];

    google.maps.event.addListener(map,'idle',function(){
      var bounds  = map.getBounds().toUrlValue(),
          rect    = 'RECTANGLE(LATLNG('+map.getBounds()
                                        .getSouthWest().toUrlValue()+'),'+
                              'LATLNG('+map.getBounds()
                                        .getNorthEast().toUrlValue()+'))',
          query   = 'SELECT '+((columns.length)?"'"+columns.join("','")+"' ":' * ')+
                    ' FROM ' + tableId + 
                    ' WHERE ST_INTERSECTS('+locationColumn+','+rect+')';

      $.get('https://www.googleapis.com/fusiontables/v2/query?sql='+
             encodeURIComponent(query)+'&key='+apiKey,function(data){
             if(bounds===map.getBounds().toUrlValue() && data.rows){
               console.log(data.rows.length + ' countries in viewport')
               if(data.rows.length){
                 var countries=[];
                 $.each(data.rows,function(i,o){
                   countries.push(o[0]);
                 });
                 console.log(countries.join(', '));
               }
             }
      },'jsonp');
    });

小提琴:(打印一个包含视口中国家/地区名称的列表)

https://jsfiddle.net/doktormolle/cgprmnk6/