Finding a set of coordinates within a certain range from latitude and longitide

后端 未结 2 1748
半阙折子戏
半阙折子戏 2020-12-15 03:04

I am working on a project in javascript involving google maps.

The goal is to figure out 16-20 coordinate points within n kilometers from a set of latitude longitude

2条回答
  •  情书的邮戳
    2020-12-15 03:16

    Basically what you're trying to do is find N points on the radius of a circle from a given point with a given radius. One simple way of doing it is splitting the 360 degrees of a circle in to N equal chunks, and finding the points at regular intervals.

    The following should do roughly what you're after -

    function findCoordinates(lat, long, range)
    {
        // How many points do we want? (should probably be function param..)
        var numberOfPoints = 16;
        var degreesPerPoint = 360 / numberOfPoints;
    
        // Keep track of the angle from centre to radius
        var currentAngle = 0;
    
        // The points on the radius will be lat+x2, long+y2
        var x2;
        var y2;
        // Track the points we generate to return at the end
        var points = [];
    
        for(var i=0; i < numberOfPoints; i++)
        {
            // X2 point will be cosine of angle * radius (range)
            x2 = Math.cos(currentAngle) * range;
            // Y2 point will be sin * range
            y2 = Math.sin(currentAngle) * range;
    
            // Assuming here you're using points for each x,y..             
            p = new Point(lat+x2, long+y2);
    
            // save to our results array
            points.push(p);
    
            // Shift our angle around for the next point
            currentAngle += degreesPerPoint;
        }
        // Return the points we've generated
        return points;
    }
    

    The array of points you get back can then easily be used to draw the circle you wish on your google map.

    If your overall goal however is just to draw a circle at a fixed radius around a point, then a far easier solution may be to use an overlay. I've found KMBox to be very easy to set up - you give it a central point, a radius and an image overlay (in your case, a transparent circle with a visible line around the edge) and it takes care of everything else, including resizing it on zoom in/out.

提交回复
热议问题