Mischa Firges
Mischa Firges

Reputation: 117

Create a square / polygon with a size in meters in Google Maps in JS

I'm going crazy soon! I've read pretty much all of the Google Maps JavaScript API V3 documentation but I can't find a way to develop the following use case:

I want to create a square / circle / polygon with a specific size in meters. The radius of the circle, or the distance between LAT and LNG in meters.

I know it's possible to measure the distance in meters between to LatLngs, but I want to create it wit that dimension.

Is there anybody who know's how to do this? That would be amazing!

Upvotes: 0

Views: 1117

Answers (1)

MrUpsidown
MrUpsidown

Reputation: 22490

You can use the Geometry library and more specifically the computeOffset method.

The distance parameter is in meters, although this is not clear from the docs.

Here is a simple example using the Rectangle class but you can use any shape. For circles, you don't need this as the radius is already expressed in meters.

For Rectangles, you need to calculate the bounds (ne for north-east and sw for south-west). Here I create a rectangle (a square in this case) with a 500 meters diagonal.

For Polygons, you need to provide a path instead of bounds, but the method remains the same. If you know the starting point, the distance and the heading between every path point, you can come up with any kind of shape.

You need to load the Geometry library in the API call: https://maps.googleapis.com/maps/api/js?libraries=geometry

function initialize() {

    var sw = new google.maps.LatLng(52.51,13.41);
    var mapOptions = {
        zoom: 13,
        center: sw,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    
    var marker = new google.maps.Marker({
        position: sw,
        map: map,
        label: 'SW'
    });
    
    var ne = google.maps.geometry.spherical.computeOffset(sw, 500, 45);
    
    var marker = new google.maps.Marker({
        position: ne,
        map: map,
        label: 'NE'
    });
    
    var rectangle = new google.maps.Rectangle({
        strokeOpacity: 0,
        strokeWeight: 0,
        fillColor: '#FF0000',
        fillOpacity: .6,
        bounds: new google.maps.LatLngBounds(sw,ne),
        map: map,
        zIndex: 0
    });
}

initialize();
#map-canvas {
  height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Upvotes: 1

Related Questions