I am making location based reminder app...but when i click on specific location then marker add to this location but when i click on submit it not show the selected location..it is getting only my current longitude and latitude...here is my code....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
this.mainClass = (MainClass) getApplication();
this.drawablered = getResources().getDrawable(R.mipmap.mainpin);
final Drawable buttonSelector = getResources().getDrawable(R.drawable.buttonselector);
this.buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
this.buttonShowSearch = (Button) findViewById(R.id.buttonShowSearch);
this.locationTextView = new AutoCompleteTextView(getApplicationContext());
this.buttonSearch = new Button(getApplicationContext());
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
this.width = displaymetrics.widthPixels;
density = displaymetrics.densityDpi;
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean available = false;
NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
available = true;
}
if (!available) {
this.mainClass.setLongToast("Sorry, there is not network connection to display the map");
}
try {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasReadContactPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
if (hasReadContactPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
124);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (this.locationManager != null) {
this.currentLocation = this.locationManager.getLastKnownLocation("gps");
if (this.currentLocation != null) {
this.currentLatitude = Double.valueOf(this.currentLocation.getLatitude());
this.currentLongitude = Double.valueOf(this.currentLocation.getLongitude());
this.currentPoint = new LatLng((int) (this.currentLatitude.doubleValue() * 1000000.0d), (int) (this.currentLongitude.doubleValue() * 1000000.0d));
locationLat = this.currentLatitude.doubleValue();
locationLong = this.currentLongitude.doubleValue();
} else {
}
} else {
}
this.buttonShowSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AddLocationActivity.this.linearLayout = (LinearLayout) AddLocationActivity.this.findViewById(R.id.layout_search);
AddLocationActivity.this.locationTextView.setHint("Location to search");
//AddLocationActivity.this.locationTextView.setTextColor(getColor(R.color.colorAccent));
AddLocationActivity.this.locationTextView.setWidth((AddLocationActivity.this.width / 4) * 3);
AddLocationActivity.this.locationTextView.setHeight(36);
AddLocationActivity.this.buttonSearch.setWidth(AddLocationActivity.this.width * 0);
AddLocationActivity.this.buttonSearch.setHeight(40);
AddLocationActivity.this.buttonSearch.setBackgroundDrawable(buttonSelector);
AddLocationActivity.this.buttonSearch.setText("Search");
AddLocationActivity.this.buttonSearch.setTextColor(-1);
AddLocationActivity.this.linearLayout.setOrientation(LinearLayout.VERTICAL);
AddLocationActivity.this.linearLayout.setVerticalGravity(16);
AddLocationActivity.this.linearLayout.addView(AddLocationActivity.this.locationTextView);
AddLocationActivity.this.linearLayout.addView(AddLocationActivity.this.buttonSearch);
AddLocationActivity.this.buttonShowSearch.setEnabled(false);
}
});
this.buttonSearch.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AddLocationActivity.this.location = AddLocationActivity.this.locationTextView.getText().toString();
AddLocationActivity.this.location.trim();
if (AddLocationActivity.this.location.compareTo("") != 0) {
AddLocationActivity.this.searchLocation();
AddLocationActivity.this.linearLayout.removeAllViews();
return;
}
AddLocationActivity.this.mainClass.setLongToast("Please enter a location");
}
});
this.buttonSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (AddLocationActivity.locationLat == 0.0d || AddLocationActivity.locationLong == 0.0d) {
AddLocationActivity.this.mainClass.setLongToast("Sorry, failed to submit");
return;
}
AddLocationActivity.this.mainClass.latitude = new StringBuilder(String.valueOf(AddLocationActivity.locationLat)).toString();
AddLocationActivity.this.mainClass.longitude = new StringBuilder(String.valueOf(AddLocationActivity.locationLong)).toString();
AddLocationActivity.this.mainClass.locationName = AddLocationActivity.locationName;
AddLocationActivity.this.finish();
}
});
}
protected void onResume() {
super.onResume();
this.mainClass.favListFlag = false;
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home_screen, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return this.mainClass.menuItemClick(item, getBaseContext());
}
protected boolean isRouteDisplayed() {
return false;
}
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
private void searchLocation() {
final Handler Modelhandler = new Handler() {
public void handleMessage(Message msg) {
AddLocationActivity.this.buttonShowSearch.setEnabled(true);
if (msg.obj == "1") {
AddLocationActivity.this.locationTextView.setText("");
AddLocationActivity.this.mainClass.setLongToast("Sorry, this location could not be marked, please mark the point manually");
} else if (msg.obj == "2") {
AddLocationActivity.this.addMarker(AddLocationActivity.this.point, AddLocationActivity.locationName);
}
}
};
new Thread() {
public void run() {
StringBuilder stringBuilder;
Message msg = new Message();
try {
((InputMethodManager) AddLocationActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AddLocationActivity.this.getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
}
String str = "";
for (int i = 0; i < AddLocationActivity.this.location.length(); i++) {
if (AddLocationActivity.this.location.substring(i, i + 1).equalsIgnoreCase(" ")) {
str = new StringBuilder(String.valueOf(str)).append("+").toString();
} else {
str = new StringBuilder(String.valueOf(str)).append(AddLocationActivity.this.location.substring(i, i + 1)).toString();
}
}
if (str.compareTo("") != 0) {
AddLocationActivity.this.location = str;
}
URL url;
HttpURLConnection connection = null;
String responseStr = "";
try {
url = new URL("http://maps.google.com/maps/api/geocode/json?address=" + AddLocationActivity.this.location + "ka&sensor=false");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(false);
DataOutputStream wr = new
DataOutputStream(connection.getOutputStream());
wr.flush();
wr.close();
// Get Response
int status = connection.getResponseCode();
BufferedInputStream in;
if (status >= 400) {
in = new BufferedInputStream(connection.getErrorStream());
} else {
in = new BufferedInputStream(connection.getInputStream());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
responseStr = response.toString();
Log.d("Server response", responseStr);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(responseStr);
} catch (JSONException e4) {
e4.printStackTrace();
}
Double d = new Double(0.0d);
d = new Double(0.0d);
Double lon1 = 0.0, lat1 = 0.0;
try {
lon1 = Double.valueOf(((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
lat1 = Double.valueOf(((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
} catch (JSONException e42) {
e42.printStackTrace();
}
if (lon1.doubleValue() == 0.0d && lat1.doubleValue() == 0.0d) {
msg.obj = "1";
} else {
AddLocationActivity.this.point = new LatLng((int) (lat1.doubleValue() * 1000000.0d), (int) (lon1.doubleValue() * 1000000.0d));
Geocoder geocoder = new Geocoder(AddLocationActivity.this.getApplicationContext(), Locale.getDefault());
try {
StringBuilder _homeAddress = new StringBuilder();
try {
List<Address> addresses = geocoder.getFromLocation(lat1.doubleValue(), lon1.doubleValue(), 1);
for (int index = 0; index < addresses.size(); index++) {
Address address = (Address) addresses.get(index);
AddLocationActivity.locationLat = lat1.doubleValue();
AddLocationActivity.locationLong = lon1.doubleValue();
if (address.getLocality() == null) {
AddLocationActivity.locationName = address.getAddressLine(0);
} else {
AddLocationActivity.locationName = address.getAddressLine(0) + ", " + address.getLocality();
}
}
stringBuilder = _homeAddress;
} catch (Exception e5) {
stringBuilder = _homeAddress;
}
} catch (Exception e6) {
}
msg.obj = "2";
}
Modelhandler.sendMessage(msg);
}
}.start();
}
private void addMarker(LatLng point, String locationName) {
if (mMap != null) {
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLng(point));
this.itemizedoverlay = new MapItemizedOverlay(this.drawablered, getApplicationContext());
this.itemizedoverlay.addOverlay(this.overlayitem);
this.mapOverlays.add(this.itemizedoverlay);
this.mv.invalidate();
if (!locationName.equals("")) {
View map_popup = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.map_popup, null);
((TextView) map_popup.findViewById(R.id.textViewLocName)).setText(locationName);
this.mainClass.toast = new Toast(getApplicationContext());
this.mainClass.toast.setDuration(Toast.LENGTH_LONG);
this.mainClass.toast.setGravity(48, 0, ((height / 2) - (height / 10)) - 60);
this.mainClass.toast.setView(map_popup);
this.mainClass.toast.show();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//this.mMap = googleMap;
LatLng sydney = new LatLng(-34.0d, 151.0d);
this.mMap.addMarker(new MarkerOptions().position(sydney).title("Sydney"));
this.mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 10.0f));
this.mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
AddLocationActivity.this.mMap.clear();
AddLocationActivity.locationLat = latLng.latitude;
AddLocationActivity.locationLong = latLng.longitude;
AddLocationActivity.this.mMap.addMarker(new MarkerOptions().position(new LatLng(AddLocationActivity.locationLat, AddLocationActivity.locationLong)).title(BuildConfig.FLAVOR + AddLocationActivity.locationLat + "\n" + AddLocationActivity.locationLong));
AddLocationActivity.this.mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(AddLocationActivity.locationLat, AddLocationActivity.locationLong), 10.9f));
}
});
}
}
Related
Currently, I have to click on the screen to get the schedule information.
I think the calender and db are loaded at the same time, but the speed at which db is loaded is slow, so it doesn't appear on the calendar right away.
But when I enter the schedule screen, I want to have the schedule information from DB appear at the bottom.
Calendar Activity: Connect to the calendar adapter and load data from the DB. When I checked on the console, the DB information is immediately imported when you enter the schedule screen.
Calendar Adapter : Bind data to the created ViewHolder, color on date (BLUE)
`
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
// get data from DB
GetData task = new GetData();
task.execute(userID);
}
private void setMonthView() {
//년 월 텍스트뷰
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
//해당 월 날짜 가져오기
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
//레이아웃 설정, 열 7개
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
setEventAdapter();
}
// 이벤트 Adapter 제공
private void setEventAdapter() {
//ID 로 목록 찾고 리스트 호출
ArrayList<Event> dailyEvents = eventsForDate(CalendarUtils.selectedDate);
EventAdapter eventAdapter = new EventAdapter(this, this, dailyEvents);
eventListView.setAdapter(eventAdapter);
}
// 새로운 이벤트 생성
public void newEventAction(View view) {
startActivity(new Intent(CalendarActivity.this, EventEditActivity.class));
}
// 재개될 때마다 다시 로드되도록 EventAdapter 호출
//Activity가 사용자와 상호작용하기 바로 전에 호출됨
#Override
protected void onResume() {
super.onResume();
setEventAdapter();
eventsList.clear();
}
// 주어진 날짜에 대한 모든 이벤트 반환
public static ArrayList<Event> eventsForDate(LocalDate date) {
events = new ArrayList<>();
for (int k = 0; k < eventsList.size(); k++) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String selectDate1 = date.toString(); //현재누른날짜
String startDate1 = eventsList.get(k).getStartdate(); //시작날짜
String endDate1 = eventsList.get(k).getEnddate(); //종료날짜
Date selectDate = null;
try {
selectDate = dateFormat.parse(selectDate1);
Date startDate = dateFormat.parse(startDate1);
Date endDate = dateFormat.parse(endDate1);
int result1 = selectDate.compareTo(startDate); // curr > d1
int result2 = selectDate.compareTo(endDate);
// 조건이 맞을때
if ((result1 >= 0) && (result2 <= 0)) //선택한 날짜가 시작날짜랑 같거나 크고 & 앤드날짜보다 작거나 같으면
events.add(eventsList.get(k)); //items.get(k)가 events 어레이에 더해짐
} catch (ParseException e) {
e.printStackTrace();
}
}
return events;
}
// 주어진 날짜에 대한 ID 반환 - 수정인지 판단
public static int eventsForID(String passedID) {
for (int i = 0; i < eventsList.size(); i++) {
String ID = eventsList.get(i).getID();
if(ID != null && passedID != null) {
//각각 일치하면 0 리턴하므로 합계 0일경우 모두 일치한다.
if (passedID.compareTo(ID)== 0) {
Log.e("compare", "ok");
return 1;
}
}
}
return 0;
}
// DB에서 이벤트 가져오기
class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(CalendarActivity.this,
"Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Log.d(TAG, "response - " + result);
if (result != null) {
mJsonString = result;
showResult();
}
}
#Override
protected String doInBackground(String... params) {
String searchKeyword1 = params[0];
String serverURL = "http://"+IP_ADDRESS+"/event_query.php";
String postParameters = "userID=" + searchKeyword1;
Log.d(TAG, "userID_event : " + searchKeyword1);
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(postParameters.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "getData: Error ", e);
errorString = e.toString();
return null;
}
}
// DB에서 array로 데이터 가져옴
public void showResult() {
try {
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
// eventsList에 저장하기 전 저장되어있던 List를 clear한 후 가져온다
eventsList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.length() != 0) {
JSONObject item = jsonArray.getJSONObject(i);
Log.d(TAG, "JSONObject : " + item);
// 해당 키워드로 DB에서 데이터를 가져온다(ID, title...)
ID = item.getString("ID");
title = item.getString("title");
startdate = item.getString("startdate");
enddate = item.getString("enddate");
alarmactive = item.getString("alarmactive");
// 가져온 데이터 eventsList에 저장
eventsList.add(new Event(ID, title, startdate, enddate, alarmactive));
Log.d(TAG, "eventsList : " + eventsList.toString());
}
}
} catch (JSONException e) {
Log.d(TAG, "showResult_member : ", e);
}
}
}
}
`
`
class CalendarAdapter extends RecyclerView.Adapter<CalendarViewHolder>
{
private final ArrayList<LocalDate> days;
private final OnItemListener onItemListener;
#NonNull
#Override
public CalendarViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.calendar_cell, parent, false);
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = (int) (parent.getHeight() * 0.199999999); //월별 달력
return new CalendarViewHolder(view, onItemListener, days);
}
// 생성된 ViewHolder 에 데이터 바인딩
#Override
public void onBindViewHolder(#NonNull CalendarViewHolder holder, int position)
{
//날짜 변수에 담기
final LocalDate date = days.get(position);
if (date == null)
//날짜가 null인 경우 홀더 날짜를 설정
holder.dayOfMonth.setText("");
else {
//그렇지 않으면 날짜 넣기
holder.dayOfMonth.setText(String.valueOf(date.getDayOfMonth()));
//선택한 날짜 회색으로 표시
if (date.equals(CalendarUtils.selectedDate)) {
holder.parentView.setBackgroundColor(Color.LTGRAY);
}
//주말 색상 지정(토요일: BLUE, 일요일: RED)
if ((position + 1) % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.BLUE);
} else if (position == 0 || position % 7 == 0) {
holder.dayOfMonth.setTextColor(Color.RED);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
for (int i = 0; CalendarActivity.eventsList.size()>i ; i++) {
Event CalendarDate1 = CalendarActivity.eventsList.get(i);
Date curr = dateFormat.parse(date.toString());
// yyyy-MM-dd
Date d1 = dateFormat.parse(CalendarDate1.startdate);
Date d2 = dateFormat.parse(CalendarDate1.enddate);
int result1 = curr.compareTo(d1); // curr > d1
int result2 = curr.compareTo(d2);
// BLUE
if ((result1 >= 0) && (result2 <= 0))
holder.parentView.setBackgroundColor(Color.parseColor("#83BBF3"));
}
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
// 전체 데이터 개수 return
#Override
public int getItemCount()
{
return days.size();
}
public interface OnItemListener
{
//해당 변수 이름은 현재날짜로 변경됨
void onItemClick(int position, LocalDate date);
}
}
`
I've moved the GetData function to another activity.
Because the code to update the data is in the calendar activity, the data is imported when the calendar is first turned on, but it cannot be modified and deleted.
In my Android project, I am showing one google map which includes my location as origin and my friends locations as destination.
As, the location data are saved in firebase. With the real time change in the location, I recall the API to show the update in the map.
But the problem is-
While showing the update in the map, it shows the updated path direction with previous one. So, all the paths are overlapped with the previous ones. But I want to regenerate the map according to the updated location.
Here's the output it shows, when the location is updated, the Marker A in the picture is my location and after update, it generates the new marker A with the previous one.
I have cleared all the originMarker, destinationMarker and polylinePaths lists. But still not working.
Here's the code of my MapActivity.js
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, DirectionFinderListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
final Intent intent = getIntent();
myLat = intent.getStringExtra("my_lat");
myLong = intent.getStringExtra("my_long");
//saving to database starts
users = new ArrayList<>();
friends = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("users");
//saving to database ends
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
btnFindPath = (Button) findViewById(R.id.btnFindPath);
etOrigin = (EditText) findViewById(R.id.etOrigin);
etDestination = (EditText) findViewById(R.id.etDestination);
}
private void sendRequest() {
originMarkers.clear();
destinationMarkers.clear();
polylinePaths.clear();
for(int i = 0; i < users.size(); i++) {
if(users.get(i).getEmail().equals(userEmail)) {
origin = users.get(i).getLatitude()+","+users.get(i).getLongitude();
}
}
String destination = etDestination.getText().toString();
try {
new DirectionFinder(this, origin, address).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
users.clear();
polylinePaths.clear();
originMarkers.clear();
destinationMarkers.clear();
for(DataSnapshot postSnapShot : dataSnapshot.getChildren()) {
User user = postSnapShot.getValue(User.class);
users.add(user);
}
for(int i = 0; i < users.size(); i++) {
if(users.get(i).getEmail().equals(userEmail) ) {
myLat = users.get(i).getLatitude();
myLong = users.get(i).getLongitude();
}
}
sendRequest();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} catch (Exception e) {
}
mMap = googleMap;
LatLng hcmus = new LatLng(Double.parseDouble(myLat), Double.parseDouble(myLong));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("My Location")
.position(hcmus)));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onDirectionFinderStart() {
try {
progressDialog = ProgressDialog.show(this, "Please wait.",
"Finding direction..!", true);
progressDialog.setCancelable(true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
} catch (Exception e) {
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
originMarkers.clear();
destinationMarkers.clear();
polylinePaths.clear();
for (Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
}
}
#Override
public void onStart() {
super.onStart();
try {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
users.clear();
address.clear();
polylinePaths.clear();
originMarkers.clear();
destinationMarkers.clear();
for(DataSnapshot postSnapShot : dataSnapshot.getChildren()) {
User user = postSnapShot.getValue(User.class);
users.add(user);
}
for(int i = 0; i < users.size(); i++) {
if(users.get(i).getLatitude() != null && users.get(i).getLongitude()!= null) {
address.add(users.get(i).getLatitude()+","+users.get(i).getLongitude());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} catch (Exception e) {
}
}
}
And here is the code to do the API call section and getting the direction to draw in map-
DirectionFinder.java
public class DirectionFinder {
private static final String DIRECTION_URL_API = "direction API url";
private static final String GOOGLE_API_KEY = "my API key";
private DirectionFinderListener listener;
private String origin;
private ArrayList<String> destination;
public DirectionFinder(DirectionFinderListener listener, String origin, ArrayList<String> destination) {
this.listener = listener;
this.origin = origin;
this.destination = destination;
}
public void execute() throws UnsupportedEncodingException {
listener.onDirectionFinderStart();
for(int i=0;i<destination.size();i++)
new DownloadRawData().execute(createUrl(destination.get(i)));
}
private String createUrl(String des) throws UnsupportedEncodingException {
String urlOrigin = URLEncoder.encode(origin, "utf-8");
String urlDestination = URLEncoder.encode(des, "utf-8");
Log.e("#LOCATION_PATH:", DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination +"&alternatives=true&key=" + GOOGLE_API_KEY);
return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination + "&alternatives=true&key=" + GOOGLE_API_KEY;
}
private class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
private List<LatLng> decodePolyLine(final String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new ArrayList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng(
lat / 100000d, lng / 100000d
));
}
return decoded;
}
}
So, I need a solution to solve the rewriting the map issue and showing only one direction path from my origin to destination. It would be very nice if someone help me to solve this problem.
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
I am creating an app. I am getting error(My app is crashed) when i find Address out of country on Google map. The reason behind it direction Route.So I want to display a message when no route found "no route found".Using a following code-
public class MainActivity extends AppCompatActivity implements OnItemClickListener, OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
GoogleMap mMap;
SupportMapFragment mFragment;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
Marker CurrentMarker, NearbyPlace, FindMarker;
LocationRequest mLocationRequest;
AutoCompleteTextView autoCompView = null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
findbtn = (Button) findViewById(R.id.findbtn);
autoCompView = (AutoCompleteTextView) findViewById(R.id.editplace);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
setListnerOnWidget();
}
private void setListnerOnWidget() {
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = autoCompView.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
};
findbtn.setOnClickListener(listener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
double mLatitude=address.getLatitude();
double mLongitude=address.getLongitude();
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=4000");
sb.append("&types=" + "liquor_store");
sb.append("&sensor=true");
sb.append("&key=AI*************************");
Log.d("Map", "<><>api: " + sb.toString());
//query places with find location
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
//for direction Route
LatLng origin = CurrentMarker.getPosition();
LatLng dest = FindMarker.getPosition();
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}
public StringBuilder sbMethod(Location location) {
//current location
double mLatitude = location.getLatitude();
double mLongitude =location.getLongitude();
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=4000");
sb.append("&types=" + "liquor_store");
sb.append("&sensor=true");
sb.append("&key=AIzaSyC47V7li_j9_M_HyYEW8D5Z2nyFYX7DkuI");
Log.d("Map", "<><>api: " + sb.toString());
return sb;
}
#Override
public void onConnected( Bundle bundle) {
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
//mGoogleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CurrentMarker = mMap.addMarker(markerOptions);
}
mLocationRequest = new LocationRequest();
//mLocationRequest.setInterval(5000); //5 seconds
// mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed( ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
if (CurrentMarker != null){
CurrentMarker.remove();
}
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));
CurrentMarker = mMap.addMarker(markerOptions);
Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
StringBuilder sbValue = new StringBuilder(sbMethod(location));
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
Log.d("result", "<><> result: " + result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
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();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
Log.d("Map", "list size: " + list.size());
// Clears all the existing markers;
if (!firstRun) {
mMap.clear();
}
firstRun = false;
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
Log.d("Map", "place: " + name);
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// Placing a marker on the touched position
NearbyPlace = mMap.addMarker(markerOptions);
}
}
}
public class Place_JSON {
//Receives a JSONObject and returns a list
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
//Retrieves all the elements in the 'places' array
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
//Invoking getPlaces with the array of json object
//where each json object represent a place
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
//Taking each place, parses and adds to list object
for (int i = 0; i < placesCount; i++) {
try {
// Call getPlace with place JSON object to parse the place
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
// Parsing the Place JSON object
private HashMap<String, String> getPlace(JSONObject jPlace)
{
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#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]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParTask parTask = new ParTask();
// Invokes the thread for parsing the JSON data
parTask.execute(result);
}
}
//A class to parse the Google Places in JSON format
private class ParTask 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]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
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 = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
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(8);
lineOptions.color(Color.GRAY);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: "+url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
//Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
DirectionsJSONParser
public class DirectionsJSONParser {
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
Please tell me how to implement message "No Route Found" when no route found Google map
Thanks
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);
}
}
}
}