简体   繁体   中英

Google Maps Circle / MySQL query

I would like to draw a circle on a map, and get all rows in my database with geo the lat/lng points that fall into that circle.

I don't want draw the circle using google.maps.Circle as that applies mercator projection distortion. I want a geometric rather than geographic circle.

So I can probably draw this to Google maps using an overlay of some sorts. But is it possible to query my database for these points?

If I were to draw a geographic circle I could use the haversine formula , but that won't work for a geometric circle.

You can use Pythagoras to find points within circle.

a^2 + b^2 = c^2

The following SQL uses PDO to find points within the radius of circle

$stmt = $dbh->prepare("SELECT  name, lat, lng, ( SQRT(POW(? - lat, 2)
                      + POW(? - lng, 2))) AS distance FROM mytable   
                       HAVING distance < ? ORDER BY distance ASC ");
    // Assign parameters
    $stmt->bindParam(1,$center_lat);//Center of circle
    $stmt->bindParam(2,$center_lng);////Center of circle
    $stmt->bindParam(3,$radius);

Javascript function if required

function Pythagoras (x1,y1,x2,y2){
    var Dist = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
return Dist ;
}

You can draw the circle using a polygon with enough segments to look ok:

 // lat, lng, and radius specify the circle // CosDeg, SinDeg are functions that accept input in degrees mPerDegLat = 110540, mPerDegLng = CosDeg(lat) * 111320; //-- mPerDegLng CORRECTED FOR LATITUDE numSegs = 64; deltaAng = 360 / numSegs; verts = []; for (i=0; i<numSegs; i++) { angle = i * deltaAng; dy = CosDeg(angle) * radius; dx = SinDeg(angle) * radius; deltaLat = dy / mPerDegLat; //-- METRES PER DEGREE deltaLng = dx / mPerDegLng; vertex = {lat:(lat + deltaLat), lng:(lng + deltaLng)}; verts.push(vertex); } polyCircle = new google.maps.Polygon({paths:verts, strokeColor...}); 

As for MySql, could you just run your query for a "geographically rectangular" area using lat, lng values with enough padding to make sure you don't miss any, and then filter the results with a script that does the inverse calculation to see if they are inside the circle?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM