How to Fetch Data From Server And Show Location
in Google Map Android Studio Programmatically

 

1. Create Project.
Select Google Maps Activity. It will create three types of files





2.  Create google Api

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.
    To get one, follow this link, follow the directions and press "Create" at  the end    
Go to this Below link and create Key 
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r
=F2:62:DC:62:4D:51:2E:8A:4D:3B:1E:C6:05:64:5E:9C:78:6A:13:D2%3Bcom.journaldev.maproutebetweenmarkers
    You can also add your credentials to an existing key, using this line:     F2:62:DC:62:4D:51:2E:8A:4D:3B:1E:C6:05:64:5E:9C:78:6A:13:D2;com.journaldev.maproutebetweenmarkers
    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key
    Once you have your key (it starts with "AIza"), replace the "google_maps_key"     string in this file.
-->

    <string name="google_maps_key" templateMergeStrategy="preserve" 
     translatable="false">YOUR_KEY_HERE (You past Generated Key)</string>
</resources>

Now Call Rest Api in this project. 1. You need to add volley library in Gradle file


implementation 'dev.dworks.libs:volleyplus:+'





2. You Need to add some permissions in manifest file

 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
 


Now in Java class


public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, 
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, 
LocationListener {
   
private ProgressBar mProgressBar;     List<DisplayData> model_list;     List<DisplayData> mylist = null;     RequestPackage p;     double dblLong, dblLati;     String str_title;     Integer int_carSpace, int_carRate, int_BikeSpace, int_bikeRate;     GoogleMap mGoogleMap;     GoogleApiClient mGoogleApiClient;     Location mLastLocation;     Marker mCurrLocationMarker;
   
@Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_maps);         postData();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(MapsActivity.this);
}
private void postData() {     //String url = entori_api + "Entori/CLIENTS_LIST";     String url = "Enter your rest Api (Web Developer will developed for you)";     p = new RequestPackage();     p.setMethod("Method of Api");     p.setUri(url);     p.setParam("Perameter", "");     // mProgressBar.setVisibility(View.VISIBLE);     new MyTask().execute(p);
}
private class MyTask extends AsyncTask<RequestPackage, String, List<DisplayData>> {
    @Override
    protected List<DisplayData> doInBackground(RequestPackage... params) {
        String content = HttpManager.getData(params[0]);
        if (content != null) {
           
try{                 mylist = new ArrayList<>();                 JSONObject jobj=new JSONObject(content);                 String status = jobj.getString("status");                 if (status == "Error"){
                }
else{
                   
String message = jobj.getString("message");                     //  txt_Result.setText(message);                     Log.e("Result:", message);                     JSONArray jsonArray = jobj.getJSONArray("ParkList");                     // List<Marker> markers = new ArrayList<>();                     mylist = new ArrayList<>();                     for(int i=0; i<jsonArray.length(); i++){
                        
DisplayData set = new DisplayData();                         JSONObject jsonObject = jsonArray.getJSONObject(i);

                        set.setCLIENT_ID((jsonObject.getInt("CLIENT_ID")));
                        set.setOWNER_NAME(jsonObject.getString("OWNER_NAME"));
                        set.setCONTACT_NUMBER(jsonObject.getString("CONTACT_NUMBER"));
                        set.setPARK_NAME(jsonObject.getString("PARK_NAME"));
                        set.setPARK_ADDRESS(jsonObject.getString("PARK_ADDRESS"));
                        set.setPARK_COUNTRY(jsonObject.getString("PARK_COUNTRY"));
                        set.setPARK_LONGITUDE(jsonObject.getDouble("PARK_LONGITUDE"));
                        set.setPARK_LATITUDE(jsonObject.getDouble("PARK_LATITUDE"));
                        set.setCAR_SPACE(jsonObject.getInt("CAR_SPACE"));
                        set.setBIKE_SPACE(jsonObject.getInt("BIKE_SPACE"));
                        set.setOTHER_SPACE(jsonObject.getInt("OTHER_SPACE"));
                        set.setCAR_RATE(jsonObject.getInt("CAR_RATE"));
                        set.setBIKE_RATE(jsonObject.getInt("BIKE_RATE"));
                        set.setOTHER_RATE(jsonObject.getInt("OTHER_RATE"));
                        mylist.add(set);
                    }
                }
               
return mylist;             } catch (JSONException e) {                 e.printStackTrace();                 return null;             }

       
} else {             Log.e("Issue",content);         }
       
return model_list;     }
   
@Override     protected void onPostExecute(List<DisplayData> displayData) {         try{
           
for(int i=0; i<mylist.size(); i++){
               
System.out.println("Longitude: " + mylist.get(i).getPARK_LONGITUDE());                 System.out.println("Latitude: " + mylist.get(i).getPARK_LATITUDE());
               
dblLati = mylist.get(i).getPARK_LATITUDE();                 dblLong = mylist.get(i).getPARK_LONGITUDE();                 str_title = mylist.get(i).getPARK_NAME();                 int_carSpace = mylist.get(i).getCAR_SPACE();                 int_carRate = mylist.get(i).getCAR_RATE();                 int_BikeSpace = mylist.get(i).getBIKE_SPACE();                 int_bikeRate = mylist.get(i).getBIKE_RATE();
               
LatLng sydney = new LatLng(dblLati, dblLong);                 mGoogleMap.addMarker(new MarkerOptions().position(sydney).title(str_title)                         .snippet("Car Space: "+int_carSpace)                 );
              
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));             }         }         catch (Exception e) {             // TODO: handle exception             System.out.println("This went wrong: " + e.getMessage());
        }

   
}
}
/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
   
mGoogleMap = googleMap;     mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
   
//mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);     // mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);     // mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    //Initialize Google Play Services    
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {         if (ContextCompat.checkSelfPermission(this,                 Manifest.permission.ACCESS_FINE_LOCATION)                 == PackageManager.PERMISSION_GRANTED) {             //Location Permission already granted             buildGoogleApiClient();             mGoogleMap.setMyLocationEnabled(true);
        }
else {             //Request Location Permission             checkLocationPermission();        }
    }
   
else {
        buildGoogleApiClient();        
mGoogleMap.setMyLocationEnabled(true);     }
}
protected synchronized void buildGoogleApiClient() {     mGoogleApiClient = new GoogleApiClient.Builder(this)             .addConnectionCallbacks(this)             .addOnConnectionFailedListener(this)             .addApi(LocationServices.API)             .build();     mGoogleApiClient.connect();
}
@Override
   
public void onConnected(Bundle bundle) {
        if (ContextCompat.checkSelfPermission(this,                 Manifest.permission.ACCESS_FINE_LOCATION)                 == PackageManager.PERMISSION_GRANTED) {         }
    }
   
@Override     public void onConnectionSuspended(int i) {}     @Override     public void onConnectionFailed(ConnectionResult connectionResult) {}
    @Override
    public void onLocationChanged(Location location) {
       
mLastLocation = location;         if (mCurrLocationMarker != null) {             mCurrLocationMarker.remove();
        }
       
//Place current location marker         LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());         MarkerOptions markerOptions = new MarkerOptions();         markerOptions.position(latLng);         markerOptions.title("And Thats Me.");         markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));         mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);         mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 200));
   
}
   
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;     private void checkLocationPermission() {         if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)                 != PackageManager.PERMISSION_GRANTED) {
           
// Should we show an explanation?             if (ActivityCompat.shouldShowRequestPermissionRationale(this,                     Manifest.permission.ACCESS_FINE_LOCATION)) {
               
// Show an explanation to the user *asynchronously* -- don't block                 // this thread waiting for the user's response! After the user                 // sees the explanation, try again to request the permission.
               
new AlertDialog.Builder(this)
                        .setTitle(
"Location Permission Needed")                         .setMessage("This app needs the Location permission, please accept to use location functionality")                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                           
@Override                             public void onClick(DialogInterface dialogInterface, int i) {                                 //Prompt the user once explanation has been shown                                 ActivityCompat.requestPermissions(MapsActivity.this,                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},                                        MY_PERMISSIONS_REQUEST_LOCATION );                             }
                        })                         .create()                         .show();
            }
else {
               
// No explanation needed, we can request the permission.                 ActivityCompat.requestPermissions(this,                         new String[]{Manifest.permission.ACCESS_FINE_LOCATION},                         MY_PERMISSIONS_REQUEST_LOCATION );             }
        }
    }
   
@Override     public void onRequestPermissionsResult(int requestCode,                                            String permissions[], int[] grantResults) {         super.onRequestPermissionsResult(requestCode, permissions, grantResults);         switch (requestCode) {             case MY_PERMISSIONS_REQUEST_LOCATION: {                 // If request is cancelled, the result arrays are empty.
               
if (grantResults.length > 0                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                     // permission was granted, yay! Do the                     // location-related task you need to do.
                   
if (ContextCompat.checkSelfPermission(this,                             Manifest.permission.ACCESS_FINE_LOCATION)                             == PackageManager.PERMISSION_GRANTED) {                         if (mGoogleApiClient == null) {                             buildGoogleApiClient();                         }                         mGoogleMap.setMyLocationEnabled(true);                     }
                }
else {                     // permission denied, boo! Disable the                     // functionality that depends on this permission.                     Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }                
return;
            }
           
// other 'case' lines to check for other             // permissions this app might request
       
}
    }
}


 Enjoy Code. 😊

Post a Comment

Previous Post Next Post