在谷歌地图上绘制一个给定地址的多边形

时间:2018-03-31 11:38:07

标签: javascript google-maps

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

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

像这样: enter image description here

1 个答案:

答案 0 :(得分:0)

下面是我近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>