Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;

import android.location.Location;

public class Main {
    /**
     * Will return a list of random location from the given position & radius
     * @param amount
     * @param lat
     * @param lng
     * @param radius
     * @return ArrayList<Location> 
     */
    public static ArrayList<Location> randomLocations(int amount, double lat, double lng, double radius) {
        ArrayList<Location> locations = new ArrayList<Location>(0);
        Location centerLocation = new Location("local");
        centerLocation.setLatitude(lat);
        centerLocation.setLongitude(lng);

        final double lngScale = Math.cos((Math.PI / 180.0) * lat);
        final double radiusDeg = radius / 111.2; // radius converted to degrees (square)

        while (locations.size() < amount) {
            Location l = new Location("local");
            double dLat = (Math.random() * radiusDeg * 2) - radiusDeg;
            double dLng = (Math.random() * radiusDeg * 2 / lngScale) - (radiusDeg / lngScale);

            l.setLatitude(centerLocation.getLatitude() + dLat);
            l.setLongitude(centerLocation.getLongitude() + dLng);
            double dist = l.distanceTo(centerLocation) / 1000.0;

            if (dist < (radius)) {
                locations.add(l);
            }
        }
        return locations;
    }
}