在谷歌地图上为给定地址绘制多边形

Posted

技术标签:

【中文标题】在谷歌地图上为给定地址绘制多边形【英文标题】:Draw a polygon on google maps for given address 【发布时间】:2018-03-31 11:38:07 【问题描述】:

我想在 Google 地图上实现一个多边形。我已经实现了用户绘图工具来绘制坐标,现在我希望当用户搜索地址时,它会在该地址边界上绘制一个多边形。我在 Google 上搜索过,但我认为 google API 本身不支持此功能,我们必须托管 KML 文件等。

那么什么是最好的实现方式,或者任何示例代码?真的很感激。

像这样: enter image description here

【问题讨论】:

如果我了解您的需求,您可以使用 Google 地理编码 API 获取人类可读街道地址的坐标。地址边界是什么意思?您想在例如公寓楼的侧面绘制线条以突出显示它们吗? 我想在一个城市、城镇或国家上绘制一个多边形。如果我能够更好地解释。我附上了一张图片,以便您更好地理解。 看看这个解决方法:***.com/a/45600181/5140781 how to get polygon in google maps URL and use it in gmaps js的可能重复 @AleemAhmad - 你搞定了吗? 【参考方案1】:

以下是我大约 4 年前为客户的概念验证创建的内容。这是最接近我相信你可能一直在要求的东西。这当然是我最近也在寻找的东西,并记得我前段时间做过。只需输入住宅地址即可进行测试。它最初是用于使用“api.geonames.org”数据绘制地震图,但这个小提琴版本被剥离以排除它。代码的要点在下面的块中。

https://jsfiddle.net/sp56ano2/

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Part II: Map Earthquakes by city/place name</title>
<style type="text/css">
    html, body, #outer-container, #map-canvas  height: 100%; margin: 0; padding: 0;
    #search 
    
        margin: 20px 0px 0px 20px;
    
    #container 
        width:100%;
        height: 100%;
        margin: 20px 20px 20px 20px;
    
    #leftcolumn 
        float:left;
        width:60%;
        height: 100%;
    
    #rightcolumn 
        float:left;
        width:40%;
    
    #map-container 
            
        width: 100%;
        height: 100%;
    
</style>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize"
  type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" ></script>
<script type="text/javascript" src="http://api.geonames.org/export/geonamesData.js?username=YOUR_USERNAME"></script>
<script type="text/javascript">

    var geocoder;
    var map;
    var username = 'YOUR_USERNAME';
    var html = '';

    var bounds = new google.maps.LatLngBounds();

    function initialize() 
        geocoder = new google.maps.Geocoder();      
        findAddress();
        searchTopEarthquakes();
    

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

    function findAddress() 
        var address = document.getElementById('location').value;
        geocoder.geocode(
            'address': address
        , function (results, status) 

            if (status == google.maps.GeocoderStatus.OK) 

                var mapOptions = 
                    zoom: 13,
                    center: results[0].geometry.location,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                

                if(!map)    
                    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
                

                var marker = new google.maps.Marker(
                    map: map,
                    position: results[0].geometry.location
                );

                var sw = results[0].geometry.bounds.getSouthWest();
                var ne = results[0].geometry.bounds.getNorthEast();
                var padding = 0.00002;
                var boxCoords = [
                    new google.maps.LatLng(ne.lat()+padding, ne.lng()+padding),
                    new google.maps.LatLng(ne.lat()+padding, sw.lng()-padding),
                    new google.maps.LatLng(sw.lat()-padding, sw.lng()-padding),
                    new google.maps.LatLng(sw.lat()-padding, ne.lng()+padding),
                    new google.maps.LatLng(ne.lat()+padding, ne.lng()+padding)
                ];
                var bbox = new google.maps.Polyline(
                    path: boxCoords,
                    geodesic: false,
                    strokeColor: '#FF0000',
                    strokeOpacity: 0.5,
                    strokeWeight: 2
                );

                bbox.setMap(map);

                // get the bounding box geonames parameters from the viewport
                var north = results[0].geometry.viewport.getNorthEast().lat();
                var south = results[0].geometry.viewport.getSouthWest().lat();
                var east = results[0].geometry.viewport.getNorthEast().lng();
                var west = results[0].geometry.viewport.getSouthWest().lng();

                //fit the map to the viewport bounding box
                map.fitBounds(results[0].geometry.viewport);

                var earthquake = 'http://api.geonames.org/earthquakesJSON?north=' + north + '&south=' + south + '&east=' + east + '&west=' + west + '&maxRows=500&username=YOUR_USERNAME';

                var infoWindows = new google.maps.InfoWindow(content: '');

                // Call Recent Earthquakes API from geonames
                $.ajax(
                    url: earthquake,
                    context: document.body
                ).done(function(data) 
                    if (data.status) 
                        document.getElementById('status').innerHTML = data.status.message;
                    
                    if (!data.earthquakes.length || (data.earthquakes.length < 1)) 
                        document.getElementById('status').innerHTML = "<b>No Result!<b>";
                        return;
                    

                    // for each earthquake item result, create a marker
                    $.each(data.earthquakes, function(key, q) 
                        var Latlng = new google.maps.LatLng(q.lat,q.lng);
                        var marker = new google.maps.Marker(
                            map: map, 
                            position: Latlng,                               
                            title:'Magnitude: ' + q.magnitude + ' Depth: ' + q.depth + ' Date: ' + q.datetime,
                        );

                        marker['infoWindow'] = 'Magnitude: ' + q.magnitude + '<br/>Depth: ' + q.depth + '<br/>Date: ' + q.datetime;

                        google.maps.event.addListener(marker, 'click', function()
                            infoWindows.setContent(marker['infoWindow']);
                            infoWindows.open(map, this);
                        )
                    );
                );

                // Center map on the location and place a marker on it
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker(
                    map: map, 
                    animation: google.maps.Animation.DROP,
                    position: results[0].geometry.location,
                    title:address,
                    icon:'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
                );

                document.getElementById('location').value = address;

             else 
                alert('Geocode could not find the location you specified for the following reasons: ' + status);
            
        );
    

    function searchTopEarthquakes()         
        d = new Date();

        request = 'http://api.geonames.org/earthquakesJSON?north=90&south=-90&east=180&west=-180&maxRows=500&date=' + d.yyyymmdd() + '&username=YOUR_USERNAME';

        $.ajax(
            url: request,
            context: document.body
        ).done(function(data) 
            if (data.status) 
                document.getElementById('topstatus').innerHTML = data.status.message;
            
            if (!data.earthquakes.length || (data.earthquakes.length < 1)) 
                document.getElementById('topstatus').innerHTML = "<b>No Result!</b>";
                return;
            

            RemoveOlderQuakes(data.earthquakes);

            var earthquakes = sortJSON(data.earthquakes, 'magnitude', 'DESC').slice(0,10);

            // for each earthquake item result, create a table row
            html = "<table style ='padding: 5px 5px 5px 5px;'>";
            $.each(earthquakes, function(key, q) 
                html = html + '<tr>';
                html = html + '<td><b>Magnitude: </b>' + q.magnitude + '</td>'
                html = html + '<td><b>Date: </b>' + q.datetime + '</td>'
                html = html + '<td><b>Depth: </b>' + q.depth + '</td>'
                html = html + '<td><b>Lng: </b>' + q.lng + '</td>'
                html = html + '<td><b>Lat: </b>' + q.lat + '</td>'                
                html = html + '</tr>';
                document.getElementById('quakes').innerHTML = html
            );
            html  = html + "</table>";
        );
      

    Date.prototype.yyyymmdd = function()                               
        var yyyy = this.getFullYear().toString();                                    
        var mm = (this.getMonth()+1).toString(); //0-based    
        var dd  = this.getDate().toString();             

        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
    ;

    function RemoveOlderQuakes(data) 
        var i = data.length;
        var d = new Date();
        d.setFullYear(d.getFullYear() - 1);
        while (i--) 
            if(data[i].datetime < d.yyyymmdd()) 
                data.splice(i, 1);
            
        
    

    function sortJSON(data, key, dir) 
        return data.sort(function(a, b) 
            var x = a[key]; var y = b[key];
            if (dir === 'ASC' )  return ((x < y) ? -1 : ((x > y) ? 1 : 0)); 
            if (dir === 'DESC')  return ((x > y) ? -1 : ((x < y) ? 1 : 0)); 
        );
    

    </script>
</head>

<body>
    <div id="outer-container">
        <div id="status"></div>
        <div id="search">
            City/location name:&nbsp;<input type="text" id="location" value="California"/>           
            <input type="button" value="Find Earthquakes" onclick="findAddress()" />
        </div>
        <div id="container">
            <div id="leftcolumn">
                <div id="map-canvas" style="width:100%; height:100%;"></div>            
            </div>
            <div id="rightcolumn">
                The top 10 largest earthquakes in the world for the last 12 months:
                <div id="topstatus"></div>
                <div id="quakes"></div>
            </div>
        </div>    
    </div>
</body>
</html>

【讨论】:

以上是关于在谷歌地图上为给定地址绘制多边形的主要内容,如果未能解决你的问题,请参考以下文章

如何使用坐标数组在谷歌地图 API 中绘制多边形?

计算在谷歌地图上绘制的多边形的面积

根据不同的纬度和长度设置谷歌地图的缩放级别

谷歌地图使用 PHP 在 MySQL 中保存多边形和点

我们如何在谷歌地图中为多边形应用可编辑标记

在谷歌地图上绘制区域