2015-11-28 55 views
4

我試圖在給定位置附近的地圖上生成隨機點。我有一個圍繞半徑爲100的用戶位置的circle形狀,並且我想在此圓形區域內生成隨機的LatLng座標。到目前爲止,我已經提出了以下功能,但點標記仍然出現在圓圈範圍之外。給定設備位置和半徑生成隨機LatLng

double lat = location.getLatitude(); 
    double lon = location.getLongitude(); 

    for (int i = 0; i < markers.size(); i++) { 
     Marker mrk = markers.get(i); 

      Random random = new Random(); 


      double radiusInDegrees =mCircle.getRadius(); 

      double u = random.nextDouble(); 
      double v = random.nextDouble(); 
      double w = radiusInDegrees * Math.sqrt(u); 
      double t = 2 * Math.PI * v; 
      double x = w * Math.cos(t); 
      double y = w * Math.sin(t); 

      // Adjust the x-coordinate for the shrinking of the east-west distances 
      double new_x = x/Math.cos(lat); 

      double newLongitude = new_x + lon; 
      double newLatitude = y + lat; 


      mrk.setPosition(new LatLng(newLatitude,newLongitude)); 

    } 

回答

1

這個答案應該有幫助。它看起來像你已經執行的將半徑從米轉換成度的東西。

// Convert radius from meters to degrees 
double radiusInDegrees = radius/111000f; 

See link here.

6

與此 https://gis.stackexchange.com/a/68275

幫助我能夠使能產生一定的半徑,其中半徑在米範圍內任意經緯度點的功能。

public LatLng getRandomLocation(LatLng point, int radius) { 

     List<LatLng> randomPoints = new ArrayList<>(); 
     List<Float> randomDistances = new ArrayList<>(); 
     Location myLocation = new Location(""); 
     myLocation.setLatitude(point.latitude); 
     myLocation.setLongitude(point.longitude); 

     //This is to generate 10 random points 
     for(int i = 0; i<10; i++) { 
      double x0 = point.latitude; 
      double y0 = point.longitude; 

      Random random = new Random(); 

      // Convert radius from meters to degrees 
      double radiusInDegrees = radius/111000f; 

      double u = random.nextDouble(); 
      double v = random.nextDouble(); 
      double w = radiusInDegrees * Math.sqrt(u); 
      double t = 2 * Math.PI * v; 
      double x = w * Math.cos(t); 
      double y = w * Math.sin(t); 

      // Adjust the x-coordinate for the shrinking of the east-west distances 
      double new_x = x/Math.cos(y0); 

      double foundLatitude = new_x + x0; 
      double foundLongitude = y + y0; 
      LatLng randomLatLng = new LatLng(foundLatitude, foundLongitude); 
      randomPoints.add(randomLatLng); 
      Location l1 = new Location(""); 
      l1.setLatitude(randomLatLng.latitude); 
      l1.setLongitude(randomLatLng.longitude); 
      randomDistances.add(l1.distanceTo(myLocation)); 
     } 
     //Get nearest point to the centre 
     int indexOfNearestPointToCentre = randomDistances.indexOf(Collections.min(randomDistances)); 
     return randomPoints.get(indexOfNearestPointToCentre); 
    } 

的for循環僅僅是確保拿到最近的隨機點,因爲我已經看到點進行走出圈子,因爲我增加半徑的目的。你可以刪除循環。