0

I want to implement a polygon on Google maps. I have implemented the user drawing tools to draw the coordinates, now I want that when a user searches for an address it draws a polygon on that address boundaries. I have searched on Google, but I think google API itself does not support this feature, we have to host KML files etc.

So what will be the best way to implement, or any example code for it? Really appreciate it.

Like this: enter image description here

Adriano
  • 3,788
  • 5
  • 32
  • 53
Aleem Ahmad
  • 33
  • 1
  • 7
  • You can use the Google Geocoding API to get the coordinates of a human-readable street address if I understand what you're after. What do you mean by the address boundaries? Do you want to trace lines on the sides of eg apartment blocks to highlight them? – ppajer Mar 31 '18 at 11:48
  • I want to draw a polygon on a city or town or country. If I am able to explain better. I have attached a picture for more understanding of yours. – Aleem Ahmad Mar 31 '18 at 12:16
  • Have a look at this workaround: https://stackoverflow.com/a/45600181/5140781 – xomena Apr 02 '18 at 12:08
  • Possible duplicate of [how to get polygon in google maps URL and use it in gmaps js](https://stackoverflow.com/questions/44480549/how-to-get-polygon-in-google-maps-url-and-use-it-in-gmaps-js) – xomena Apr 02 '18 at 12:13
  • @AleemAhmad - Did you get this working? – Birdy Apr 23 '18 at 08:34

1 Answers1

0

Below is what I created almost 4 years ago for a proof of concept for a client. It's the closest thing to what I believe you may have been asking for. It's certainly what I was also looking for just recently and remembered I did this some time ago. Just type in a residential address to test it. It was originally for plotting earthquakes using "api.geonames.org" data, but this fiddle version was stripped down to exclude it. The gist of the code is in the block below.

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>