Jan Genvher Papica
Jan Genvher Papica

Reputation: 151

Android Studio - How to add markers randomly on a school map using google map api

Hello I currently developing an app that could track a user inside the school campus. my problem is when running the MapsActivity it couldn't track the users location instantly sometimes I am waiting up to a minute before the location or marker will appear.

My solution is to add initial point/marker location of a user randomly on the school map and it will be overwrite by the exact location after the app gets the exact location.

How can I add marker randomly? Now I am using volley to get locations list from mysql server.

here is the code:

  @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_help);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            e_date = extras.getString("e_date");
            e_type = extras.getString("e_type");
            e_position = extras.getString("e_position");
            e_desc = extras.getString("e_desc");
            e_user_id = extras.getString("e_user_id");

        }
//        Toast.makeText(SendHelp.this, e_date, Toast.LENGTH_LONG).show();
//        Toast.makeText(SendHelp.this, e_type, Toast.LENGTH_LONG).show();
//        Toast.makeText(SendHelp.this, e_position, Toast.LENGTH_LONG).show();
//        Toast.makeText(SendHelp.this, e_desc, Toast.LENGTH_LONG).show();
//        Toast.makeText(SendHelp.this, e_user_id, Toast.LENGTH_LONG).show();



        points = new ArrayList<LatLng>(); //added
        latLngList = new ArrayList<LatLng>();
        WifiManager manager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo info = manager.getConnectionInfo();
        final int ip = info.getIpAddress();
        final String ipAddress = BigInteger.valueOf(ip).toString();


        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mlocListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                if(currentLocationMarker != null){
                    currentLocationMarker.remove();
                }

                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                final LatLng latLng = new LatLng(latitude, longitude);

                points.add(latLng); //added
//                redrawLine();

                MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng);
                markerOptions.title(e_user_id).snippet(e_position);

                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                currentLocationMarker = mMap.addMarker(markerOptions);
//                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.2f));


                current_loc = latLng.toString();



//                Toast.makeText(SendHelp.this, ipAddress, Toast.LENGTH_LONG).show();




                StringRequest stringRequest = new StringRequest(Request.Method.POST, loc_url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
//                                    try {
//                                        JSONArray jsonArray= new JSONArray(response);
//                                        JSONObject jsonObject = jsonArray.getJSONObject(0);
//                                        String code = jsonObject.getString("code");
//                                        String message = jsonObject.getString("message");
//                                        builder.setTitle("Server Response");
//                                        builder.setMessage(message);
//                                        displayAlert(code);
//
//                                    } catch (JSONException e) {
//                                        e.printStackTrace();
//                                    }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("current_loc", current_loc);
                        params.put("user_id", e_user_id);
                        return params;


                    }


                };
                MySingleton.getInstance(SendHelp.this).addToRequestQueue(stringRequest);

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }


        };



        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        provider = locationManager.getBestProvider(criteria, true);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }


        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, mlocListener);

Upvotes: 2

Views: 1213

Answers (1)

androidAhmed
androidAhmed

Reputation: 237

you can add lat and lng you have of your school location to the map in the first and navigate camera to this position then it will override with the data from server

lets say your school has this latitude and langitude

       double latitude = 12.3659;
       double longitude = 33.689;
       final LatLng latLng = new LatLng(latitude, longitude);
            MarkerOptions markerOptions = new MarkerOptions(); 
       markerOptions.position(latLng);

and set camera position

    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(newLatLng)                         
                            .zoom(18)                          
                              .build();
           map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

the marker will update with next data from server

if you need the position be changed every time here is code from solve stackover flow answered by Abhishek

Generate random LatLng given device location and radius

with the help of this https://gis.stackexchange.com/a/68275

I am able to make a function which generate random LatLng point within certain radius, where radius is in meter.

  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);
}

The purpose of for loop is just to ensure to get nearest random point, as I have seen points were getting out of circle as I am increasing the radius. You may remove loop.

Upvotes: 1

Related Questions