【问题标题】:google maps, fusion tables and markers谷歌地图,融合表和标记
【发布时间】:2016-07-23 19:28:50
【问题描述】:

我在文档中到处搜索以解释如何仅显示融合表给定区域的标记。

目前所有标记都出现在地图上,如下所示:

Fusion Table Google Maps

JSFiddle (note jsfiddle wont load the uri from website so markers wont show)

如果您单击融合表/谷歌地图的某个区域,我会按预期在弹出窗口中获得该区域名称,但是我最初不想显示任何标记。单击融合表/地图的某个区域时,我希望它仅显示该给定区域的标记,而不是整个地图。

这就是我从 Web Api 向地图添加标记的方式:

         var uri = 'http://mountainsandweather.azurewebsites.net/api/Mountains';

            $(document).ready(function () {
                //Get web api json data
                $.getJSON(uri)
                    .done(function (data) {
                        // On success, 'data' contains a list of mountains.
                        $.each(data, function (key, item) {
                            // Add a list item for the mountain.
                            $('<li>', { text: formatItem(item) }).appendTo($('#mountains'));

                            //Put seperate data fields into one variable 
                            var latLng = new google.maps.LatLng(item.Latitude, item.Longitude);

                            //Add info window to each marker
                            var infowindow = new google.maps.InfoWindow({
                                content: formatItemInfoWindow(item)
                            });


                            // Creating a marker and putting it on the map
                            var marker = new google.maps.Marker({
                                position: latLng,
                                title: formatItemInfoWindow(item.Name),
                                infowindow: infowindow
                            });
                            marker.setMap(map);
                            google.maps.event.addListener(marker, 'click', function () {
                                //this.infowindow.close(); //not working correctly info windows still show
                                this.infowindow.open(map, marker);

                            });      
                        });
                    });
            });
            function formatItemInfoWindow(item) {
                return item.Name + '<br />' + item.Height_ft + '<br />' + item.humidity + '<br />' + item.snowCover + '<br />' + item.temperature;
            }
            function formatItem(item) {
                return item.Latitude +', '+ item.Longitude;
            }
        }

我确实在文档中看到了可以添加到融合表中的 where 语句。像这样:

 var layer = new google.maps.FusionTablesLayer({
                    query: {
                        select: 'geometry',
                        from: '11RJmSNdTr7uC867rr2zyzNQ6AiE1hcREmGFTlvH3'
                        where: //not sure if I could use this or what to put.
                    },

但是,来自 Web Api 的数据并没有被分割成特定的区域,它只是一个很长的纬度和经度列表。像这样:

<Mountain>
<Height_ft>2999</Height_ft>
<Height_m>914</Height_m>
<ID>c1</ID>
<Latitude>57.588007</Latitude>
<Longitude>-5.5233564</Longitude>
<Name>Beinn Dearg</Name>
<humidity>0.81</humidity>
<snowCover>4.99</snowCover>
<temperature>63</temperature>
</Mountain>

谷歌有什么方法可以将融合表几何与坐标混合吗?显示给定区域的所有标记的简单方法?或者任何人都可以想到可以做到这一点的方法吗?

一些关于 webapi 的额外细节以防需要:

    private MountainContext db = new MountainContext();

    // GET: api/Mountains
    public IQueryable<Mountain> GetMountains()
    {
        return db.Mountains;
    }

    // GET: api/Mountains/5
    [ResponseType(typeof(Mountain))]
    public IHttpActionResult GetMountain(string id)
    {
        Mountain mountain = db.Mountains.Find(id);
        if (mountain == null)
        {
            return NotFound();
        }

        return Ok(mountain);
    }
    public IQueryable<Mountain> GetMountainByName(string name)
    {

        return db.Mountains.Where(n => string.Equals(n.Name, name));
    }

【问题讨论】:

  • 您是否可以选择将标记也存储在 FusionTable 中?

标签: javascript jquery asp.net google-maps asp.net-web-api


【解决方案1】:

很遗憾,FusionTablesLayer 中没有 containsLocation 函数。

一种解决方案是从 FusionTablesLayer 创建 Google Maps Polygon,允许我们使用 containsLocation 来确定是否将标记添加到地图。

首先我们需要坐标来创建多边形。我们可以使用google.visualization.Query从融合表中获取选定区域的坐标:

function getMountainPolygonFromFusionTable(label) {
    // Return a new promise.
    return new Promise(function(resolve, reject) {

    var sql = encodeURIComponent("SELECT 'geometry' FROM 11RJmSNdTr7uC867rr2zyzNQ6AiE1hcREmGFTlvH3 WHERE label ='" + label + "'");
    var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);

    query.send(function (response) {
        var data = response.getDataTable().getValue(0, 0);
        // Create a XML parser
        if (window.DOMParser) {
            var parser = new DOMParser();
            var kml = parser.parseFromString(data, "text/xml");
        } else { 
            var kml = new ActiveXObject("Microsoft.XMLDOM");
            kml.loadXML(data);
        }

        // Get the coordinates of Mountain Areas
        var latLngs = kml.getElementsByTagName("coordinates")[0].childNodes[0].nodeValue.split(' ');

        var mountainPolygonLatLngs = [];
        for (var i = 0; i < latLngs.length; i++) {
            var latLng = latLngs[i].split(',');
            mountainPolygonLatLngs.push(new google.maps.LatLng(latLng[1], latLng[0]));
        }

        // Create the polygon
        mountainPolygons = new google.maps.Polygon({
            paths: mountainPolygonLatLngs,
            fillColor: 'transparent',
            strokeColor : 'transparent'
        });

        resolve(mountainPolygons);

    });

  });
}

然后我们只循环遍历山脉数组并检查所选区域是否包含山脉:

// On mountain area click
google.maps.event.addListener(layer, 'click', function(event) {

    // Clear all markers
    while(markers.length) { 
      markers.pop().setMap(null); 
    }

    // Get Polygon from FustionTable
    getMountainPolygonFromFusionTable(event.row.label.value).then(function(mountainPolygons) {

    // Loop through the mountains
    for(var i = 0; i < mountains.length; i++) {

        // Get the mountain LatLng
        var mountain = mountains[i];
        var mountainLat = mountain.getElementsByTagName("Latitude")[0].childNodes[0].nodeValue;
        var mountainLng = mountain.getElementsByTagName("Longitude")[0].childNodes[0].nodeValue;
        var mountainLatLng = new google.maps.LatLng(mountainLat, mountainLng);

        // If mountain is in the selected polygon, create a marker for it.
        if (google.maps.geometry.poly.containsLocation(mountainLatLng, mountainPolygons)) {

            // @todo set infowindow, title...
            var marker = new google.maps.Marker({
                position: mountainLatLng,
                title: 'Marker info here',
            });
            marker.setMap(map);
            markers.push(marker);

        }
    }

  });
}); 

这是 JSON 版本:

google.maps.event.addListener(layer, 'click', function(event) {

    // Clear all markers
    while(markers.length) { 
        markers.pop().setMap(null); 
    }

    // Get Polygone from FustionTable
    getMountainPolygonFromFusionTable(event.row.label.value).then(function(mountainPolygons) {

        $.getJSON(uri).done(function (data) {

            // On success, 'data' contains a list of mountains.
            $.each(data, function (key, item) {

                //Put seperate data fields into one variable 
                var latLng = new google.maps.LatLng(item.Latitude, item.Longitude);

                if (google.maps.geometry.poly.containsLocation(latLng, mountainPolygons)) {

                    // @todo set infowindow, title...
                    var marker = new google.maps.Marker({
                        position: latLng,
                        title: 'Marker info here',
                    });
                    marker.setMap(map);
                    markers.push(marker);

                }

            });

        });
    });
}); 

Here's the Fiddle - XML

Here's the Fiddle - JSON

And here's what the JSON API might look like

【讨论】:

  • @GarrithGraham,啊,确实想知道,但您示例中的 URL 指向 XML。我添加了一个 JSON 版本:jsfiddle.net/chriswatts91/9wu90dze/6
  • @GarrithGraham Bizarre,示例中使用的 JSON 遵循 API 文档:mountainsandweather.azurewebsites.net/Help/Api/…,除非有什么不同?您有正在使用的 API 的链接吗?
  • 那个或者你的 getMountainPolygonFromFusionTable 函数不适用于 web api?
  • google.visualization.Query 似乎缺少 jsapi 库。尝试在我们的脚本之前添加&lt;script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;,在google.maps.event.addDomListener(window, 'load', init);之前添加google.load('visualization', '1.0');
  • 嗯,我没有那个脚本,但其余的应该没问题。我用我的 web api (MVC) 中的布局的完整代码更新了我的问题
猜你喜欢
  • 1970-01-01
  • 2011-10-23
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 2015-08-02
相关资源
最近更新 更多