Home > Back-end >  How to make multiple rectangles not using hard-coding in google maps api?
How to make multiple rectangles not using hard-coding in google maps api?

Time:09-04

let map, infoWindow;

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 37.460074, lng: 126.952568 },
    zoom: 16,
  }
);


    const rectangle = new google.maps.Rectangle({
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map,
        bounds: new google.maps.LatLngBounds(
            new google.maps.LatLng(20.39623, 77.85009),
            new google.maps.LatLng(24.39623, 80.85009)
            )
    });

    infoWindow = new google.maps.InfoWindow();

    const locationButton = document.createElement("button");

    locationButton.textContent = "Pan to Current Location";
    locationButton.classList.add("custom-map-control-button");
    map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
    locationButton.addEventListener("click", () => {
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
        (position) => {
            const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent("Location found.");
            infoWindow.open(map);
            map.setCenter(pos);
        },
        () => {
            handleLocationError(true, infoWindow, map.getCenter());
        }
        );
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
    });
    }

    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(
    browserHasGeolocation
        ? "Error: The Geolocation service failed."
        : "Error: Your browser doesn't support geolocation."
    );
    infoWindow.open(map);
}

window.initMap = initMap;

I already know to make one rectangle in google maps api, but I don't know how to make multiple rectangles with using loops. I don't want to make all rectangles with using hard-coding like rectangle1, rectangle2. I expect that I have to change variable named bounds, but I don't know how to do it. How can I use loops to make many rectangles?

CodePudding user response:

The specific requirements / objectives are a little vague but based upon the comment that they (multiple rectangles) are to be next to one another! then some simple arithmetic using the LatLngBounds for the initial rectangle can be done to determine either the difference in east/west ( to effectively get the width of the rectangle ) or the north/south ( to effectively get the height of the rectangle )

With those differences you can easily plot the new lat/lng values and this draw a new rectangle.

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: </title>
        <style>
            #map{
                width:800px;
                height:600px;
                float:none;
                margin:auto;
            }
            .gm-bttn{
                padding:1rem;
                color:gold;
                margin:0.25rem;
                border-radius:1rem;
                border:none;
                background:purple;
                transition:ease-in-out all 500ms;
                cursor:pointer;
            }
            .gm-bttn:hover{
                background:gold;
                color:purple
            }
        </style>
        <script>
            function initMap() {
                let shapes=[];
                let map = new google.maps.Map( document.getElementById("map"), {
                    center: { lat: 37.460074, lng: 126.952568 },
                    zoom: 16,
                });
                
                // your original rectangle bounds
                let bounds=new google.maps.LatLngBounds(
                    new google.maps.LatLng(20.39623, 77.85009),
                    new google.maps.LatLng(24.39623, 80.85009)
                );
                
                // for convenience, convert bounds to json
                let json=bounds.toJSON();
                let delta={
                    long:Math.abs( json.west - json.east ),
                    lat:Math.abs( json.north - json.south )
                };
                
                // create your original rectangle.
                shapes.push(
                    new google.maps.Rectangle({
                        strokeColor: "#FF0000",
                        strokeOpacity: 0.8,
                        strokeWeight: 2,
                        fillColor: "#FF0000",
                        fillOpacity: 0.1,
                        map,
                        geodesic:true,
                        bounds:bounds
                    })
                );
                
                // A ring around the globe of rectangles...
                let max=360 / Math.abs( delta.long );
                
                for( let i=1; i < max; i   ){
                    // modify json based upon delta values for lat/lng
                    json.east -= delta.long,
                    json.west -= delta.long;
                    
                    // and then add a new rectangle
                    shapes.push(
                        new google.maps.Rectangle({
                            strokeColor: "#FF0000",
                            strokeOpacity: 0.8,
                            strokeWeight: 2,
                            fillColor: "#FF0000",
                            fillOpacity: 0.1,
                            map,
                            geodesic:true,
                            bounds:json
                        })
                    );
                }
                

                let infoWindow = new google.maps.InfoWindow();
                
                let clear=document.createElement('button');
                    clear.textContent='Remove rectangles'
                    clear.className='gm-bttn';
                    clear.addEventListener('click',( e )=>shapes.forEach( n=>n.setMap( null ) ) );

                let bttn = document.createElement('button');
                    bttn.textContent='Pan to Current Location';
                    bttn.className='gm-bttn';
                    
                    bttn.addEventListener("click", (e)=>{
                        const errorhandler=()=>{
                            infoWindow.setPosition( map.getCenter() );
                            infoWindow.setContent( navigator.geolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.' );
                            infoWindow.open( map );
                            return false;
                        };
                        const successhandler=( position )=>{
                            const pos = {
                                lat: position.coords.latitude,
                                lng: position.coords.longitude,
                            };
                            infoWindow.setPosition( pos );
                            infoWindow.setContent( "Location found." );
                            infoWindow.open( map );
                            map.setCenter( pos );
                            return true;
                        };
                        const config={
                            enableHighAccuracy:true,
                            timeout:Infinity,
                            maximumAge:60000
                        };
                        if( navigator.geolocation ) {
                            navigator.geolocation.getCurrentPosition( successhandler, errorhandler, config );
                            return true;
                        }
                        return errorhandler();
                    });
                
                map.controls[ google.maps.ControlPosition.TOP_CENTER ].push( bttn );
                map.controls[ google.maps.ControlPosition.TOP_CENTER ].push( clear );
                map.setCenter( bounds.getCenter() );
                map.fitBounds( bounds );
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=<APIKEY>&callback=initMap'></script>
    </head>
    <body>
        <div id='map'></div>
    </body>
</html> 

Check out the for example...

The same could be done for Latitude values if you wish - or both to completely cover the globe.

  • Related