How mapbox navigation draw(Polyline) user location changed coordinates on Map? - java

private static class LocationChangeListeningActivityLocationCallback
implements LocationEngineCallback<LocationEngineResult> {
private final WeakReference<MapMatchingActivity> activityWeakReference;
LocationChangeListeningActivityLocationCallback(MapMatchingActivity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
#Override
public void onSuccess(LocationEngineResult result) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Location location = result.getLastLocation();
Feature feature = Feature.fromGeometry(Point.fromLngLat(result.getLastLocation().getLongitude(),result.getLastLocation().getLatitude()));
if (location == null) {
return;
}
Log.e("Coords", String.valueOf(result.getLastLocation().getLatitude() +" " + result.getLastLocation().getLongitude()));
String[] latlong = (result.getLastLocation().getLatitude() +"," + result.getLastLocation().getLongitude()).split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
latLngList.add(new LatLng(longitude,latitude));
// activity.drawMarker();
}
}
#Override
public void onFailure(#NonNull Exception exception) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Toast.makeText(activity, exception.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The above code where I am getting user location coordinates, I got to know that MapBox updated SDK, and PolylineOptions is now Deprecated, I have drawn lines using LineOptions but still have No idea how to update based on user location Please check below code.
private void getDirection(List<LatLng> coordinates,LatLng latLng){
List<LatLng> latLngs = new ArrayList<>();
latLngs.add(new LatLng(21.23504447 ,72.81109308));
latLngs.add(new LatLng( 21.23471482921968, 72.81101793050766));
latLngs.add(new LatLng(21.23425981047001, 72.81080335378647));
LineOptions lineOptions = new LineOptions()
.withLatLngs(latLngs)
.withLineColor(ColorUtils.colorToRgbaString(Color.BLACK))
.withLineWidth(5.0f);
lineManager.create(lineOptions);
}

Related

Google ARCore Sceneform How to detect ray hit to ar object

I am new to Google AR core and Sceneform. I want to develop a basic fps game on Android Studio, when user touches anywhere on the screen AR object will be created and if button is pushed, a ray will be shot from the center of the screen and if the ray hits to any created AR object, the score will increase.
The code is below, but i cannot continue more. How can i do?
public class MainActivity extends AppCompatActivity{
private static final String TAG = MainActivity.class.getSimpleName();
private static final double MIN_OPENGL_VERSION = 3.0;
private ArFragment arFragment;
private ModelRenderable mRenderable;
private ImageButton imageButton;
private TextView scoreText;
private int score=0;
private Set<Vector3> position = new HashSet<Vector3>();
// Set<Vector3> obj_set = new HashSet<Vector3>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkIsSupportedDeviceOrFinish(this)) {
return;
}
setContentView(R.layout.activity_main);
arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
imageButton = (ImageButton) findViewById(R.id.imageButton);
scoreText = (TextView) findViewById(R.id.scoreText);
setUpModel();
setUpPlane();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Camera camera = arFragment.getArSceneView().getScene().getCamera();
Ray ray = new Ray(camera.getWorldPosition(),camera.getForward());
HitTestResult result = arFragment.getArSceneView().getScene().hitTest(ray);
if (result.getNode() != null && result.getDistance() < 0) {
// Hit something
//doSomething(result.getNode());
Log.e(TAG,"RAYCASTING ERROR");
}else{
Iterator value = position.iterator();
while(value.hasNext()){
if(position.equals(result.getPoint())){
Toast.makeText(getApplicationContext(),"HIT WAS DETECTED",Toast.LENGTH_SHORT).show();
score = score + 5;
scoreText.setText("SCORE: " + score + "");
Log.e(TAG,"HEY THERE");
}
else{
Log.e(TAG,"NOOOOOOO");
}
}
}
} catch (Exception e) {
Log.e(TAG, "ERROR ON BUTTON");
}
}
});
}
private void setUpModel() { //Load the model
WeakReference<MainActivity> weakActivity = new WeakReference<>(this);
ModelRenderable.builder()
.setSource(this, R.raw.model)
.setIsFilamentGltf(true)
.build()
.thenAccept(modelRenderable -> {
MainActivity activity = weakActivity.get();
if (activity != null) {
mRenderable = modelRenderable;
}
})
.exceptionally(throwable -> {
Toast.makeText(MainActivity.this, "Model can not be loaded!", Toast.LENGTH_SHORT).show();
return null;
});
}
private void setUpPlane() {//Attach the scene to the node
arFragment.setOnTapArPlaneListener(new BaseArFragment.OnTapArPlaneListener() {
#Override
public void onTapPlane(HitResult hitResult, Plane plane, MotionEvent motionEvent) {
// Creates the anchor
Anchor anchor = hitResult.createAnchor();
AnchorNode anchorNode = new AnchorNode(anchor);
anchorNode.setParent(arFragment.getArSceneView().getScene());
createModel(anchorNode);
}
});
}
private void createModel(AnchorNode anchorNode) {// Create the transformable model and add it to the anchor
TransformableNode node = new TransformableNode(arFragment.getTransformationSystem());
node.setParent(anchorNode);
node.setRenderable(mRenderable);
node.select();
position.add(anchorNode.getWorldPosition());
}
public static boolean checkIsSupportedDeviceOrFinish(final Activity activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Log.e(TAG, "Sceneform requires Android N or later");
Toast.makeText(activity, "Sceneform requires Android N or later", Toast.LENGTH_LONG).show();
activity.finish();
return false;
}
String openGlVersionString =
((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE))
.getDeviceConfigurationInfo()
.getGlEsVersion();
if (Double.parseDouble(openGlVersionString) < MIN_OPENGL_VERSION) {
Log.e(TAG, "Sceneform requires OpenGL ES 3.0 later");
Toast.makeText(activity, "Sceneform requires OpenGL ES 3.0 or later", Toast.LENGTH_LONG)
.show();
activity.finish();
return false;
}
return true;
}
}
I'm not sure if I fully understood what you want to achieve but if you want to increase score when user points towards the object and presses button then you could check just that the result != null and then do your action, why do you have the hit detection logic in the else part? So you could have:
...
HitTestResult result = arFragment.getArSceneView().getScene().hitTest(ray);
if (result.getNode() != null) {
// Hit something
Toast.makeText(getApplicationContext(),"HIT WAS DETECTED",Toast.LENGTH_SHORT).show();
score = score + 5;
scoreText.setText("SCORE: " + score + "");
}
...
This will of course keep the score increasing as long as the user points towards the object.

Android Google Maps API - cannot resolve "location.setLatitude()"

I'm trying to create a location and set latitude and longitude, but when I write
location.setLatitude
I'm getting
cannot resolve symbol
error. Anyone can help?
Location location = new Location("");
location.setLatitude(0.0d);
If I change code like this:
Location location = new Location("")
.setLatitude(0.0d)
I'm getting error
Incopatible types. ;
Required: android.location.Location ;
Found: void
Edit: Here's the class. It's literally code from Google tutorial. I deleted some unnecessary parts, and added few i needed.
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback {
private static final String TAG = MapsActivity.class.getSimpleName();
private GoogleMap mMap;
private CameraPosition mCameraPosition;
// The entry points to the Places API.
private GeoDataClient mGeoDataClient;
private PlaceDetectionClient mPlaceDetectionClient;
// The entry point to the Fused Location Provider.
private FusedLocationProviderClient mFusedLocationProviderClient;
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private final LatLng mDefaultLocation = new LatLng(49.656639, 19.636917);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// Used for selecting the current place.
private static final int M_MAX_ENTRIES = 5;
private String[] mLikelyPlaceNames;
private String[] mLikelyPlaceAddresses;
private String[] mLikelyPlaceAttributions;
private LatLng[] mLikelyPlaceLatLngs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// Construct a GeoDataClient.
mGeoDataClient = Places.getGeoDataClient(this, null);
// Construct a PlaceDetectionClient.
mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
// Build the map.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Saves the state of the map when the activity is paused.
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
if (mMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
LatLng centPoint = new LatLng(49.656639, 19.636917);
int kolStrefa = Color.argb(40, 255, 0, 0);
Location location = new Location("");
location.setLatitude(0.0d); //Cannot resolve symbol
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
// Prompt the user for permission.
getLocationPermission();
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
CircleOptions strefa = new CircleOptions()
.center(centPoint)
.radius(200)
.strokeColor(Color.RED)
.fillColor(kolStrefa);
Circle circle = mMap.addCircle(strefa);
}
double distance = mLastKnownLocation.distanceTo(krzCent);
/**
* Gets the current location of the device, and positions the map's camera.
*/
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.getResult();
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
/**
* Prompts the user for permission to use the device location.
*/
private void getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
/**
* Handles the result of the request for location permissions.
*/
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
/**
* Prompts the user to select the current place from a list of likely places, and shows the
* current place on the map - provided the user has granted location permission.
*/
private void showCurrentPlace() {
if (mMap == null) {
return;
}
if (mLocationPermissionGranted) {
// Get the likely places - that is, the businesses and other points of interest that
// are the best match for the device's current location.
#SuppressWarnings("MissingPermission") final
Task<PlaceLikelihoodBufferResponse> placeResult =
mPlaceDetectionClient.getCurrentPlace(null);
placeResult.addOnCompleteListener
(new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
#Override
public void onComplete(#NonNull Task<PlaceLikelihoodBufferResponse> task) {
if (task.isSuccessful() && task.getResult() != null) {
PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
// Set the count, handling cases where less than 5 entries are returned.
int count;
if (likelyPlaces.getCount() < M_MAX_ENTRIES) {
count = likelyPlaces.getCount();
} else {
count = M_MAX_ENTRIES;
}
int i = 0;
mLikelyPlaceNames = new String[count];
mLikelyPlaceAddresses = new String[count];
mLikelyPlaceAttributions = new String[count];
mLikelyPlaceLatLngs = new LatLng[count];
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
// Build a list of likely places to show the user.
mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
.getAddress();
mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
.getAttributions();
mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if (i > (count - 1)) {
break;
}
}
// Release the place likelihood buffer, to avoid memory leaks.
likelyPlaces.release();
// Show a dialog offering the user the list of likely places, and add a
// marker at the selected place.
openPlacesDialog();
} else {
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
} else {
// The user has not granted permission.
Log.i(TAG, "The user did not grant location permission.");
// Add a default marker, because the user hasn't selected a place.
mMap.addMarker(new MarkerOptions()
.title("DEF")
.position(mDefaultLocation)
.snippet("DEFfd"));
// Prompt the user for permission.
getLocationPermission();
}
}
/**
* Displays a form allowing the user to select a place from a list of likely places.
*/
private void openPlacesDialog() {
// Ask the user to choose the place where they are now.
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// The "which" argument contains the position of the selected item.
LatLng markerLatLng = mLikelyPlaceLatLngs[which];
String markerSnippet = mLikelyPlaceAddresses[which];
if (mLikelyPlaceAttributions[which] != null) {
markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
}
// Add a marker for the selected place, with an info window
// showing information about that place.
mMap.addMarker(new MarkerOptions()
.title(mLikelyPlaceNames[which])
.position(markerLatLng)
.snippet(markerSnippet));
// Position the map's camera at the location of the marker.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
DEFAULT_ZOOM));
}
};
// Display the dialog.
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
}
First, you should try to create a completely new class and create this Location there to see if the error lies within the rest of the code.
And finally,
Location location = new Location("").setLatitude(0.0d); will not work because you first create your Location and then instantly set the latitude. Java thinks that you want to assign the return value of #setLatitude to the variable (which of course is not possible since it returns void).

Skipped 1492 frames! The application may be doing too much work on its main thread.How to show loader while skipping frames in app? [duplicate]

This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
As I am new to android I couldn't fix this skipped 1000+ frames issue.Help me to sort out this and help me to add loading progress bar while this skipping frames action takes place before opening map. This is my map code.
RouteMap.java
public class RouteMap extends android.support.v4.app.FragmentActivity
implements OnClickListener, OnInfoWindowClickListener,
DirecitonReceivedListener, OnMapReadyCallback {
public List<String> destinations;
ImageView img_home, img_menu;
private GoogleMap mMap;
ProgressDialog prgDialog;
model modelData;
private Button btnDirection;
double latitude, longitude;
LinearLayout linear_back;
LatLng startPosition, start;
String startPositionTitle;
Vibrator vibrator;
String startPositionSnippet;
Double desc1_long, desc1_lat;
LatLng destinationPosition1;
String destinationPositionTitle;
String destinationPositionSnippet;
MarkerOptions mDestination1, mStart;
ToggleButton tbMode;
GPSTracker gps;
Geocoder gCoder;
ArrayList<Address> addresses = null;
ArrayList<Address> adres2 = null;
SupportMapFragment mapFragment;
public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
TextView back_txt;
openMap openMap;
String mapStatus = "start";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_map);
back_txt = (TextView) findViewById(R.id.txt_back);
try {
back_txt = (TextView) findViewById(R.id.txt_back);
modelData = model.getInstance();
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
gCoder = new Geocoder(RouteMap.this);
addresses = (ArrayList<Address>) gCoder.getFromLocation(latitude, longitude, 1);
tbMode = (ToggleButton) findViewById(R.id.tbMode);
mapFragment = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
btnDirection = (Button) findViewById(R.id.btnDirection);
btnDirection.setOnClickListener(this);
tbMode.setChecked(true);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
public int calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {
final int R = 6371;
try {
Double latDistance = deg2rad(venueLat - userLat);
Double lonDistance = deg2rad(venueLng - userLng);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(venueLat))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = 0 - 0;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return (int) Math.sqrt(distance);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Please Check your Destination's GeoCode ", Toast.LENGTH_LONG).show();
}
return 0;
}
private double deg2rad(double deg) {return (deg * Math.PI / 180.0);}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap=googleMap;
//setUpMap();
try {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
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;
}
mMap.setMyLocationEnabled(true);
mMap.setIndoorEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setAllGesturesEnabled(true);
String[] arr = new String[modelData.outletList.size()];
for(int i=0;i<modelData.outletList.size();i++)
{
String str1 = modelData.outletList.get(i)[2];
String str2 = modelData.outletList.get(i)[3];
String newString = str1+","+str2;
arr[i] = newString;
}
String[] latTempArr = arr;
String strKey = "";
double curLatitude = latitude;
double curLongtitude = longitude;
double desLat;
double desLng;
Map<String, Integer> final_arr = new HashMap<String, Integer>();
Map<String, Integer> final_arr2 = new HashMap<String, Integer>();
List<Integer> intTempArr = new ArrayList<Integer>();
List<Integer> intTempArr2 = new ArrayList<Integer>();
for(int j=0;j<arr.length;j++)
{
intTempArr = new ArrayList<Integer>();
for (int k=0;k<latTempArr.length;k++)
{
String[] arr_temp = latTempArr[k].split(",");
//System.out.println(arr_temp[0]);
desLat = Double.parseDouble(arr_temp[0]);
desLng = Double.parseDouble(arr_temp[1]);
int temp = calculateDistance(curLatitude,curLongtitude,desLat,desLng);
intTempArr.add(temp);
final_arr.put(latTempArr[k],temp);
}
Collections.sort(intTempArr);
Integer[] array = new Integer[intTempArr.size()];
intTempArr.toArray(array);
for (Map.Entry<String, Integer> entry : final_arr.entrySet()) {
try{
if (entry.getValue().equals(array[0])) { //get next best path
List<String> list = new ArrayList<String>(Arrays.asList(latTempArr)); // remove the best path to find next one
list.remove(entry.getKey());
latTempArr = list.toArray(new String[0]);
String[] arr_temp2 = entry.getKey().split(",");
//System.out.println(arr_temp[0]);
curLatitude = Double.parseDouble(arr_temp2[0]);
curLongtitude = Double.parseDouble(arr_temp2[1]);
strKey = entry.getKey();
intTempArr2.add(entry.getValue());
final_arr2.put(strKey,entry.getValue());
}
}
catch(Exception e)
{
}
}
//System.out.println(intTempArr);
}
//int i = 0;
destinations = new ArrayList<String>();
for(int i =0;i<intTempArr2.size();i++) {
for(String Key : final_arr2.keySet()) {
//System.out.println();
if(final_arr2.get(Key) == intTempArr2.get(i)) {
destinations.add(Key);
break;
}
}
}
System.out.println(destinations);
for(int i = 0;i < destinations.size();i++) {
//Toast.makeText(getApplicationContext(), " ListItem : " + i, Toast.LENGTH_LONG).show();
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+"," +" "+ addresses.get(0).getAddressLine(2);
try {
adres2 = (ArrayList<Address>) gCoder.getFromLocation(desc1_lat, desc1_long, 1);
} catch (IOException e) {
e.printStackTrace();
}
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+"," +" "+adres2.get(0).getAddressLine(2);
// mMap.setOnInfoWindowClickListener(this);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.marker, null);
TextView info= (TextView) v.findViewById(R.id.info);
info.setText(marker.getSnippet().toString());
return v;
}
});
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
latitude = desc1_lat;
longitude = desc1_long;
LatLng locations = new LatLng(latitude,longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 5.5f));
}
}catch (Exception ex)
{
/*Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();*/
}
}
public void clearMap() {
mMap.clear();
}
#Override
public void onClick(View v) {
try
{
Locale mLocale = new Locale("en");
Log.d("Display language = ", "" + mLocale.getDisplayLanguage());
gCoder = new Geocoder(RouteMap.this,mLocale);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
for(int i = 0;i<destinations.size();i++) {
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+","+" "+addresses.get(0).getAddressLine(2);
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+","+""+ adres2.get(0).getAddressLine(2);
mMap.setOnInfoWindowClickListener(this);
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
if (v == btnDirection) {
// clearMap();
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
if (tbMode.isChecked()) {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_DRIVING, this)
.execute();
} else {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_WALKING, this)
.execute();
}
}
latitude = desc1_lat;
longitude = desc1_long;
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
#Override
public void OnDirectionListReceived(List<LatLng> mPointList) {
try
{
if (mPointList != null) {
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i < mPointList.size(); i++) {
rectLine.add(mPointList.get(i));
}
mMap.addPolyline(rectLine);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
start = new LatLng(latitude, longitude);
CameraPosition mCPFrom = new CameraPosition.Builder()
.target(start).zoom(15.5f).bearing(0).tilt(25)
.build();
final CameraPosition mCPTo = new CameraPosition.Builder()
.target(destinationPosition1).zoom(15.5f).bearing(0)
.tilt(50).build();
changeCamera(CameraUpdateFactory.newCameraPosition(mCPFrom),
new CancelableCallback() {
#Override
public void onFinish() {
changeCamera(CameraUpdateFactory
.newCameraPosition(mCPTo),
new CancelableCallback() {
#Override
public void onFinish() {
LatLngBounds bounds = new LatLngBounds.Builder()
.include(start)
.include(
destinationPosition1)
.build();
changeCamera(
CameraUpdateFactory
.newLatLngBounds(
bounds, 50),
null, false);
}
#Override
public void onCancel() {
}
}, false);
}
#Override
public void onCancel() {
}
}, true);
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data Connection", Toast.LENGTH_LONG).show();
}
}
private void changeCamera(CameraUpdate update, CancelableCallback callback,
boolean instant) {
if (instant) {
mMap.animateCamera(update, 1, callback);
} else {
mMap.animateCamera(update, 4000, callback);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onInfoWindowClick(Marker marker) {
}
private class openMap extends AsyncTask<String, Void, String>
{
ProgressDialog mProgressDialog;
Context ctx;
public openMap(Context ctx)
{
this.ctx=ctx;
mProgressDialog = new ProgressDialog(RouteMap.this);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Loading Map..Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
// Toast.makeText(getApplicationContext(), "Syncing DB...", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... urls)
{
return "Success";
}
#Override
protected void onPostExecute(String result)
{
mProgressDialog.dismiss();
try
{
if(result.equalsIgnoreCase("Success")) {
}
else
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}catch (Exception e){}
}
}
}
From this code above what changes should I make to fix the Skipped
1000+ frames issue and also help me add loader before opening the
map...
Geocoder.getFromLocation() is an expensive call that does a network call to Google's servers, so don't make it on the UI thread.
Have a look at Processes and Threads in the android developer docs for various ways of making the request in the background.
The code that you write in OnMapReady function is to much, please remove that code from there I can see there are more then 4 "for" loops in onMapReady, move that part to to some where else like OnCreate() create all maps and lists that you want.
Just ues OnMapReady function for placing markers

Map route between your current location and a fixed marker can't make polylines

I want to make a route between my current location and marker not sure how to follow. I added a marker on the map but it doesn't show the polylines. For example when the user starts the app, they should get a route from their location to the marker.I am really stack on this.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
ArrayList < LatLng > MarkerPoints;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList < > ();
// 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);
}
/**
* 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) {
mMap = googleMap;
//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) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions().position(new LatLng(34.701466, 33.029269)).title("UMAR"));
// Already two locations
if (MarkerPoints.size() > 1) {
MarkerPoints.clear();
mMap.clear();
}
}
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#
Override
public void onMapClick(LatLng point) {
// Adding new item to the ArrayList
MarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if (MarkerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MarkerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Checks, whether start and end locations are captured
if (MarkerPoints.size() >= 2) {
LatLng origin = MarkerPoints.get(0);
LatLng dest = MarkerPoints.get(1);
// Getting URL to the Google Directions API
String url = getUrl(origin, dest);
Log.d("onMapClick", url.toString());
FetchUrl FetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
FetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
});
}
private String getUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask < String, Void, String > {
#
Override
protected String doInBackground(String...url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#
Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask < String, Integer, List < List < HashMap < String, String >>> > {
// Parsing the data in non-ui thread
#
Override
protected List < List < HashMap < String, String >>> doInBackground(String...jsonData) {
JSONObject jObject;
List < List < HashMap < String, String >>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
Log.d("ParserTask", jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("ParserTask", "Executing routes");
Log.d("ParserTask", routes.toString());
} catch (Exception e) {
Log.d("ParserTask", e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#
Override
protected void onPostExecute(List < List < HashMap < String, String >>> result) {
ArrayList < LatLng > points;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList < > ();
lineOptions = new PolylineOptions();
// Fetching i-th route
List < HashMap < String, String >> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap < String, String > point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(10);
lineOptions.color(Color.RED);
Log.d("onPostExecute", "onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
mMap.addPolyline(lineOptions);
} else {
Log.d("onPostExecute", "without Polylines drawn");
}
}
}
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) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#
Override
public void onConnectionSuspended(int i) {
}
#
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("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#
Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#
Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] 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. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}

Android - Cant get latitude/longitude value to store and pass on variable

I am trying to store the latitude/longitude to variables x3 and x4 to pass on Spot[] array but it returns 0. I tried printing it on onConnected method and it works fine.
I also tried other methods to add marker on google map and I put map.addMarker on onConnected method instead but my app closes. If u can suggest where to put addMarker please do. Thanks.
GoogleMap map;
private static Location mLastLocation;
private static GoogleApiClient mGoogleApiClient;
static double x3;
static double x4;
LatLng userloc;
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
x3 = mLastLocation.getLatitude();
x4 = mLastLocation.getLongitude();
userloc = new LatLng(x3,x4);
txtPlateno.setText(String.valueOf(x3+" - "+x4)); // PRINT TEST ONLY WITH CORRECT RESULT
}
}
private static Spot[] SPOTS_ARRAY = new Spot[]{
new Spot("YOU ARE HERE", "DESC ", "", new LatLng(x3, x4)), // NOT SHOWN IN MAP AT ALL
new Spot("Besabella Parking Lot",
"Address: Sta Cruz Labogon, Mandaue City\n " +
"Fee: \n " +
"No. of available space: \n " +
"Distance:" + x3 + "KM", "", new LatLng(10.351763, 123.953683)),
// TESTING x3 ON DISTANCE WITH RESULT 0.0
};
You can call add marker after getting lat/long and also can move camera on that for reference you can check following code
public class MapDialogFragment extends DialogFragment implements LibListner, OnClickListener, OnInfoWindowClickListener {
private View dialog;
private MarkerOptions markerOptions;
private SupportMapFragment mMapFragment;
private GoogleMap mMap;
private TextView tvBackText, tvback;
// private ArrayList<String> getClickedTitle;
private ArrayList<Data> newData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Utility.Log("onCreateView");
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// //
getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// getDialog().getWindow()
// .getAttributes().windowAnimations = R.style.DialogAnimation;
if (dialog != null) {
ViewGroup parent = (ViewGroup) dialog.getParent();
if (parent != null)
parent.removeView(dialog);
}
try {
dialog = inflater.inflate(R.layout.dlg_map, container, false);
} catch (Exception e) {
/* map is already there, just return view as it is */
}
return dialog;
}
#Override
public void onStart() {
super.onStart();
// Utility.Log("onStart");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Utility.Log("onCreate");
FragmentManager fm = getChildFragmentManager();
mMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.mapView);
if (mMapFragment == null) {
mMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapView, mMapFragment).commit();
}
}
#Override
public void onActivityCreated(Bundle arg0) {
super.onActivityCreated(arg0);
init();
loadMap();
initMap();
listner();
}
private void loadMap() {
String map = Utility.BASE_URL + "mall/location";
new GetLibResponse(MapDialogFragment.this, new LocationGeneralModel(), getActivity(), map, Utility.LOCATIONCOMMON, true, true);
}
#Override
public void onResume() {
super.onResume();
try {
int chkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
markerOptions = new MarkerOptions();
if (chkGooglePlayServices != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(chkGooglePlayServices, getActivity(), 1122).show();
} else {
mMap = mMapFragment.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
mMap.setMyLocationEnabled(false);
mMap.setOnInfoWindowClickListener(this);
// if (isSearch) {
// mMap.setOnMapClickListener(MapDialogFragment.this);
// mMap.setOnMapLongClickListener(MapDialogFragment.this);
// mMap.setOnMarkerDragListener(MapDialogFragment.this);
//
// if (latitude != null && longitude != null && latitude != "" && longitude != "") {
// mMap.clear();
// markerOptions
// .position(
// new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)));
// mMap.addMarker(markerOptions);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)),
// 15.0f));
//
// }
// } else {
// mMap.clear();
// markerOptions
// .position(
// new LatLng(Double.parseDouble(flat), Double.parseDouble(flong)));
// mMap.addMarker(markerOptions);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// new LatLng(Double.parseDouble(flat), Double.parseDouble(flong)),
// 15.0f));
// }
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
tvback = (TextView) dialog.findViewById(R.id.frg_location_tvBack);
tvback.setOnClickListener(this);
tvBackText = (TextView) dialog.findViewById(R.id.frg_location_tvBackText);
tvBackText.setOnClickListener(this);
}
private void listner() {
}
private void initMap() {
}
private MainFragmentActivity mainActivity() {
return ((MainFragmentActivity) getActivity());
}
#Override
public void onResponseComplete(Object clsGson, int requestCode) {
if (requestCode == Utility.LOCATIONCOMMON) {
if (mainActivity() != null) {
mainActivity().mLocationGeneralModel = (LocationGeneralModel) clsGson;
if ((mainActivity().mLocationGeneralModel != null) && (mainActivity().mLocationGeneralModel.data != null)
&& (mainActivity().mLocationGeneralModel.data.size() != 0)) {
ArrayList<Double> vLat = new ArrayList<Double>();
ArrayList<Double> vLong = new ArrayList<Double>();
ArrayList<String> vName = new ArrayList<String>();
ArrayList<Data> newData = new ArrayList<LocationGeneralModel.Data>();
for (int pin = 0; pin < mainActivity().mLocationGeneralModel.data.size(); pin++) {
try {
if (!mainActivity().mLocationGeneralModel.data.get(pin).vLat.equals("")) {
// Log.d("TAG", mainActivity().mLocationGeneralModel.data.get(pin).vLat);
vLat.add(Double.parseDouble(mainActivity().mLocationGeneralModel.data.get(pin).vLat));
vLong.add(Double.parseDouble(mainActivity().mLocationGeneralModel.data.get(pin).vLong));
vName.add((mainActivity().mLocationGeneralModel.data.get(pin).vName_en));
double vLatitude[] = new double[vLat.size()];
double vLongitude[] = new double[vLong.size()];
for (int getArray = 0; getArray < vLat.size(); getArray++) {
vLatitude[getArray] = vLat.get(getArray);
vLongitude[getArray] = vLong.get(getArray);
newData.add(mainActivity().mLocationGeneralModel.data.get(pin));
}
multipleMarker(vLatitude, vLongitude, vName, newData);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
#Override
public void onResponseError(String errorMessage, int requestCode) {
}
private void multipleMarker(double latitude[], double longitude[], ArrayList<String> vName, ArrayList<Data> newData) {
this.newData = newData;
mMap.clear();
// LatLngBounds.Builder builder = new LatLngBounds.Builder();
// for (Marker marker : markers) {
// builder.include(marker.getPosition());
// }
// LatLngBounds bounds = builder.build();
// getClickedTitle = new ArrayList<String>();
for (int i = 0; i < latitude.length; i++) {
// Log.d("TAG", "Marker Add" + latitude[i] + " " + longitude[i]);
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude[i], longitude[i])).title(vName.get(i));
mMap.addMarker(marker);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude[i], longitude[i]), 5));
}
// getClickedTitle = vName;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.frg_location_tvBack:
dismiss();
break;
case R.id.frg_location_tvBackText:
dismiss();
break;
}
}
#Override
public void onInfoWindowClick(Marker arg0) {
for (int counter = 0; counter < newData.size(); counter++) {
if (arg0.getTitle().equals(newData.get(counter).vName_en)) {
Data data = newData.get(counter);
MallPerticularsFragment mFragment = new MallPerticularsFragment();
Bundle bundle = new Bundle();
bundle.putString("mall_name", data.vName_en);
bundle.putString("mall_locEn", data.vLocation);
mFragment.setArguments(bundle);
((MainFragmentActivity) getActivity()).displayFragmentWithArg(mFragment);
}
}
}
}

Categories

Resources