[TF][MAPS] replace Google Maps with OSMDroid: LocationActivity

(cherry picked from commit 1c93d5a569f1bd15408b21fca0f621cdd8addd90)
This commit is contained in:
thermatk 2020-04-04 10:19:59 +00:00 committed by 世界
parent a76fb317cc
commit 5999186123
No known key found for this signature in database
GPG Key ID: CD109927C34A63C4
10 changed files with 335 additions and 274 deletions

View File

@ -23,11 +23,10 @@ dependencies {
compileOnly 'org.checkerframework:checker-qual:2.5.2' compileOnly 'org.checkerframework:checker-qual:2.5.2'
compileOnly 'org.checkerframework:checker-compat-qual:2.5.0' compileOnly 'org.checkerframework:checker-compat-qual:2.5.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.googlecode.mp4parser:isoparser:1.0.6' implementation 'com.googlecode.mp4parser:isoparser:1.0.6'
implementation 'com.stripe:stripe-android:2.0.2' implementation 'com.stripe:stripe-android:2.0.2'
implementation 'com.google.code.gson:gson:2.8.6' implementation 'com.google.code.gson:gson:2.8.6'
implementation 'org.osmdroid:osmdroid-android:6.1.6'
} }
//return an api key from a properties file. //return an api key from a properties file.
@ -436,5 +435,3 @@ private static File findJavac() {
return null return null
} }
} }
apply plugin: 'com.google.gms.google-services'

View File

@ -9,12 +9,9 @@
<uses-feature android:name="android.hardware.location" android:required="false" /> <uses-feature android:name="android.hardware.location" android:required="false" />
<uses-feature android:name="android.hardware.LOCATION" android:required="false" /> <uses-feature android:name="android.hardware.LOCATION" android:required="false" />
<uses-permission android:name="${applicationId}.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="${applicationId}.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<application <application
android:allowBackup="false" android:allowBackup="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"

View File

@ -9,13 +9,10 @@
<uses-feature android:name="android.hardware.location" android:required="false" /> <uses-feature android:name="android.hardware.location" android:required="false" />
<uses-feature android:name="android.hardware.LOCATION" android:required="false" /> <uses-feature android:name="android.hardware.LOCATION" android:required="false" />
<uses-permission android:name="${applicationId}.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<permission android:name="${applicationId}.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<application <application
android:allowBackup="false" android:allowBackup="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"

View File

@ -9,12 +9,9 @@
<uses-feature android:name="android.hardware.location" android:required="false" /> <uses-feature android:name="android.hardware.location" android:required="false" />
<uses-feature android:name="android.hardware.LOCATION" android:required="false" /> <uses-feature android:name="android.hardware.LOCATION" android:required="false" />
<uses-permission android:name="${applicationId}.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="${applicationId}.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<application <application
android:allowBackup="false" android:allowBackup="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"

View File

@ -9,13 +9,10 @@
<uses-feature android:name="android.hardware.location" android:required="false" /> <uses-feature android:name="android.hardware.location" android:required="false" />
<uses-feature android:name="android.hardware.LOCATION" android:required="false" /> <uses-feature android:name="android.hardware.LOCATION" android:required="false" />
<uses-permission android:name="${applicationId}.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<permission android:name="${applicationId}.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<application <application
android:allowBackup="false" android:allowBackup="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"

View File

@ -25,4 +25,9 @@
-keep class com.google.android.exoplayer2.decoder.SimpleOutputBuffer { *; } -keep class com.google.android.exoplayer2.decoder.SimpleOutputBuffer { *; }
# Use -keep to explicitly keep any other classes shrinking would remove # Use -keep to explicitly keep any other classes shrinking would remove
-dontoptimize -dontoptimize
-dontobfuscate -dontobfuscate
# https://github.com/osmdroid/osmdroid/issues/633
-dontwarn org.osmdroid.tileprovider.modules.NetworkAvailabliltyCheck
# Osmdroid
-dontwarn org.osmdroid.**

View File

@ -575,27 +575,6 @@ public class AndroidUtilities {
public static boolean isGoogleMapsInstalled(final BaseFragment fragment) { public static boolean isGoogleMapsInstalled(final BaseFragment fragment) {
return true; return true;
/*try {
ApplicationLoader.applicationContext.getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
if (fragment.getParentActivity() == null) {
return false;
}
AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
builder.setMessage(LocaleController.getString("InstallGoogleMaps", R.string.InstallGoogleMaps));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.maps"));
fragment.getParentActivity().startActivityForResult(intent, 500);
} catch (Exception e1) {
FileLog.e(e1);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
fragment.showDialog(builder.create());
return false;
}*/
} }
public static int[] toIntArray(List<Integer> integers) { public static int[] toIntArray(List<Integer> integers) {

View File

@ -19,7 +19,7 @@ import android.text.TextUtils;
import android.view.Gravity; import android.view.Gravity;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import com.google.android.gms.maps.model.LatLng; import org.osmdroid.util.GeoPoint;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ContactsController; import org.telegram.messenger.ContactsController;
@ -225,9 +225,9 @@ public class SharingLiveLocationCell extends FrameLayout {
} }
} }
LatLng position = info.marker.getPosition(); GeoPoint position = info.marker.getPosition();
location.setLatitude(position.latitude); location.setLatitude(position.getLatitude());
location.setLongitude(position.longitude); location.setLongitude(position.getLongitude());
String time = LocaleController.formatLocationUpdateDate(info.object.edit_date != 0 ? info.object.edit_date : info.object.date); String time = LocaleController.formatLocationUpdateDate(info.object.edit_date != 0 ? info.object.edit_date : info.object.date);
if (userLocation != null) { if (userLocation != null) {

View File

@ -4,6 +4,7 @@
* You should have received a copy of the license in this archive (see LICENSE). * You should have received a copy of the license in this archive (see LICENSE).
* *
* Copyright Nikolai Kudashov, 2013-2018. * Copyright Nikolai Kudashov, 2013-2018.
* Copyright Ruslan Boitsov, 2017-2020.
*/ */
package org.telegram.ui; package org.telegram.ui;
@ -32,6 +33,7 @@ import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect; import android.graphics.Rect;
import android.graphics.RectF; import android.graphics.RectF;
import android.graphics.Shader; import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.location.Location; import android.location.Location;
import android.location.LocationManager; import android.location.LocationManager;
@ -39,6 +41,8 @@ import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.SparseArray; import android.util.SparseArray;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
import android.view.MotionEvent; import android.view.MotionEvent;
@ -52,23 +56,26 @@ import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdate; import org.osmdroid.api.IGeoPoint;
import com.google.android.gms.maps.CameraUpdateFactory; import org.osmdroid.api.IMapController;
import com.google.android.gms.maps.GoogleMap; import org.osmdroid.config.Configuration;
import com.google.android.gms.maps.MapView; import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import com.google.android.gms.maps.MapsInitializer; import org.osmdroid.events.ZoomEvent;
import com.google.android.gms.maps.Projection; import org.osmdroid.tileprovider.tilesource.ITileSource;
import com.google.android.gms.maps.model.BitmapDescriptorFactory; import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import com.google.android.gms.maps.model.CameraPosition; import org.osmdroid.tileprovider.tilesource.XYTileSource;
import com.google.android.gms.maps.model.CircleOptions; import org.osmdroid.util.BoundingBox;
import com.google.android.gms.maps.model.LatLng; import org.osmdroid.views.MapView;
import com.google.android.gms.maps.model.LatLngBounds; import org.osmdroid.util.GeoPoint;
import com.google.android.gms.maps.model.MapStyleOptions; import org.osmdroid.views.Projection;
import com.google.android.gms.maps.model.Marker; import org.osmdroid.views.overlay.Marker;
import com.google.android.gms.maps.model.MarkerOptions; import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.IMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildConfig;
import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatObject;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageLocation;
@ -131,9 +138,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
private ActionBarMenuItem searchItem; private ActionBarMenuItem searchItem;
private MapOverlayView overlayView; private MapOverlayView overlayView;
private GoogleMap googleMap;
private MapView mapView; private MapView mapView;
private CameraUpdate forceUpdate; private IGeoPoint forceUpdate;
private float yOffset; private float yOffset;
private boolean scrolling; private boolean scrolling;
@ -149,6 +155,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
private ActionBarMenuItem otherItem; private ActionBarMenuItem otherItem;
private ChatActivity parentFragment; private ChatActivity parentFragment;
private TextView attributionOverlay;
private boolean currentMapStyleDark; private boolean currentMapStyleDark;
private boolean checkGpsEnabled = true; private boolean checkGpsEnabled = true;
@ -191,7 +199,6 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
private boolean userLocationMoved; private boolean userLocationMoved;
private boolean searchedForCustomLocations; private boolean searchedForCustomLocations;
private boolean firstWas; private boolean firstWas;
private CircleOptions circleOptions;
private LocationActivityDelegate delegate; private LocationActivityDelegate delegate;
private int locationType; private int locationType;
@ -200,9 +207,11 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
private final static int open_in = 1; private final static int open_in = 1;
private final static int share_live_location = 5; private final static int share_live_location = 5;
private final static int map_list_menu_map = 2; private final static int map_list_menu_osm = 2;
private final static int map_list_menu_satellite = 3; private final static int map_list_menu_wiki = 3;
private final static int map_list_menu_hybrid = 4; private final static int map_list_menu_cartodark = 4;
private MyLocationNewOverlay myLocationOverlay;
public final static int LOCATION_TYPE_SEND = 0; public final static int LOCATION_TYPE_SEND = 0;
public final static int LOCATION_TYPE_SEND_WITH_LIVE = 1; public final static int LOCATION_TYPE_SEND_WITH_LIVE = 1;
@ -263,8 +272,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
super(context); super(context);
} }
public void addInfoView(Marker marker) { public void addInfoView(Marker marker, VenueLocation location) {
VenueLocation location = (VenueLocation) marker.getTag();
if (lastPressedVenue == location) { if (lastPressedVenue == location) {
return; return;
} }
@ -367,7 +375,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
views.put(marker, frameLayout); views.put(marker, frameLayout);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()), 300, null); final IMapController controller = mapView.getController();
controller.animateTo(marker.getPosition(),mapView.getZoomLevelDouble(),300L);
} }
public void removeInfoView(Marker marker) { public void removeInfoView(Marker marker) {
@ -377,16 +386,16 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
views.remove(marker); views.remove(marker);
} }
} }
//TODO
public void updatePositions() { public void updatePositions() {
if (googleMap == null) { if (mapView == null) {
return; return;
} }
Projection projection = googleMap.getProjection(); Projection projection = mapView.getProjection();
for (HashMap.Entry<Marker, View> entry : views.entrySet()) { for (HashMap.Entry<Marker, View> entry : views.entrySet()) {
Marker marker = entry.getKey(); Marker marker = entry.getKey();
View view = entry.getValue(); View view = entry.getValue();
Point point = projection.toScreenLocation(marker.getPosition()); Point point = projection.toPixels(marker.getPosition(),null);
view.setTranslationX(point.x - view.getMeasuredWidth() / 2); view.setTranslationX(point.x - view.getMeasuredWidth() / 2);
view.setTranslationY(point.y - view.getMeasuredHeight() + AndroidUtilities.dp(22)); view.setTranslationY(point.y - view.getMeasuredHeight() + AndroidUtilities.dp(22));
} }
@ -422,20 +431,9 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
getNotificationCenter().removeObserver(this, NotificationCenter.closeChats); getNotificationCenter().removeObserver(this, NotificationCenter.closeChats);
getNotificationCenter().removeObserver(this, NotificationCenter.didReceiveNewMessages); getNotificationCenter().removeObserver(this, NotificationCenter.didReceiveNewMessages);
getNotificationCenter().removeObserver(this, NotificationCenter.replaceMessagesObjects); getNotificationCenter().removeObserver(this, NotificationCenter.replaceMessagesObjects);
try { // TODO
if (googleMap != null) { // proper exit, like upstream does with
googleMap.setMyLocationEnabled(false); // setMyLocationEnabled(false);
}
} catch (Exception e) {
FileLog.e(e);
}
try {
if (mapView != null) {
mapView.onDestroy();
}
} catch (Exception e) {
FileLog.e(e);
}
if (adapter != null) { if (adapter != null) {
adapter.destroy(); adapter.destroy();
} }
@ -683,9 +681,9 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
mapTypeButton.setSubMenuOpenSide(2); mapTypeButton.setSubMenuOpenSide(2);
mapTypeButton.setAdditionalXOffset(AndroidUtilities.dp(10)); mapTypeButton.setAdditionalXOffset(AndroidUtilities.dp(10));
mapTypeButton.setAdditionalYOffset(-AndroidUtilities.dp(10)); mapTypeButton.setAdditionalYOffset(-AndroidUtilities.dp(10));
mapTypeButton.addSubItem(map_list_menu_map, R.drawable.msg_map, LocaleController.getString("Map", R.string.Map)); mapTypeButton.addSubItem(map_list_menu_osm, R.drawable.msg_map, "Standard OSM");
mapTypeButton.addSubItem(map_list_menu_satellite, R.drawable.msg_satellite, LocaleController.getString("Satellite", R.string.Satellite)); mapTypeButton.addSubItem(map_list_menu_wiki, R.drawable.msg_map, "Wikimedia");
mapTypeButton.addSubItem(map_list_menu_hybrid, R.drawable.msg_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid)); mapTypeButton.addSubItem(map_list_menu_cartodark, R.drawable.msg_map, "Carto Dark");
mapTypeButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); mapTypeButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground)); Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) { if (Build.VERSION.SDK_INT < 21) {
@ -712,18 +710,37 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
mapViewClip.addView(mapTypeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12, 12, 0)); mapViewClip.addView(mapTypeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12, 12, 0));
mapTypeButton.setOnClickListener(v -> mapTypeButton.toggleSubMenu()); mapTypeButton.setOnClickListener(v -> mapTypeButton.toggleSubMenu());
mapTypeButton.setDelegate(id -> { mapTypeButton.setDelegate(id -> {
if (googleMap == null) { if (mapView == null) {
return; return;
} }
if (id == map_list_menu_map) { if (id == map_list_menu_osm) {
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
} else if (id == map_list_menu_satellite) { mapView.setTileSource(TileSourceFactory.MAPNIK);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); } else if (id == map_list_menu_wiki) {
} else if (id == map_list_menu_hybrid) { // Create a custom tile source
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); ITileSource tileSource = new XYTileSource(
"Wikimedia", 0, 19,
256, ".png",
new String[] {"https://maps.wikimedia.org/osm-intl/"},
"© OpenStreetMap contributors");
attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
mapView.setTileSource(tileSource);
} else if (id == map_list_menu_cartodark) {
// Create a custom tile source
ITileSource tileSource = new XYTileSource(
"Carto Dark", 0, 20,
256, ".png",
new String[] {
"https://cartodb-basemaps-a.global.ssl.fastly.net/dark_all/",
"https://cartodb-basemaps-b.global.ssl.fastly.net/dark_all/",
"https://cartodb-basemaps-c.global.ssl.fastly.net/dark_all/",
"https://cartodb-basemaps-d.global.ssl.fastly.net/dark_all/"},
"© OpenStreetMap contributors, © CARTO");
attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, © <a href=\"https://carto.com/attributions\">CARTO</a>"));
mapView.setTileSource(tileSource);
} }
}); });
mapViewClip.addView(getAttributionOverlay(context), LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM, LocaleController.isRTL ? 0 : 4, 0, LocaleController.isRTL ? 4 : 0, 20));
locationButton = new ImageView(context); locationButton = new ImageView(context);
drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground)); drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) { if (Build.VERSION.SDK_INT < 21) {
@ -765,17 +782,19 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
} }
if (messageObject != null || chatLocation != null) { if (messageObject != null || chatLocation != null) {
if (myLocation != null && googleMap != null) { if (myLocation != null && mapView != null) {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()), googleMap.getMaxZoomLevel() - 4)); final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()),mapView.getMaxZoomLevel() -2, null);
} }
} else { } else {
if (myLocation != null && googleMap != null) { if (myLocation != null && mapView != null) {
locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY));
locationButton.setTag(Theme.key_location_actionActiveIcon); locationButton.setTag(Theme.key_location_actionActiveIcon);
adapter.setCustomLocation(null); adapter.setCustomLocation(null);
userLocationMoved = false; userLocationMoved = false;
showSearchPlacesButton(false); showSearchPlacesButton(false);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()))); final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()));
if (searchedForCustomLocations) { if (searchedForCustomLocations) {
if (myLocation != null) { if (myLocation != null) {
adapter.searchPlacesWithQuery(null, myLocation, true, true); adapter.searchPlacesWithQuery(null, myLocation, true, true);
@ -900,12 +919,14 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
} }
} else if (locationType == LOCATION_TYPE_GROUP_VIEW) { } else if (locationType == LOCATION_TYPE_GROUP_VIEW) {
if (googleMap != null) { if (mapView != null) {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(chatLocation.geo_point.lat, chatLocation.geo_point._long), googleMap.getMaxZoomLevel() - 4)); final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(chatLocation.geo_point.lat, chatLocation.geo_point._long),mapView.getMaxZoomLevel() -2, null);
} }
} else if (position == 1 && messageObject != null && !messageObject.isLiveLocation()) { } else if (position == 1 && messageObject != null && !messageObject.isLiveLocation()) {
if (googleMap != null) { if (mapView != null) {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long), googleMap.getMaxZoomLevel() - 4)); final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long),mapView.getMaxZoomLevel() -2, null);
} }
} else if (position == 1 && locationType != 2) { } else if (position == 1 && locationType != 2) {
if (delegate != null && userLocation != null) { if (delegate != null && userLocation != null) {
@ -948,7 +969,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
} else if (object instanceof LiveLocation) { } else if (object instanceof LiveLocation) {
LiveLocation liveLocation = (LiveLocation) object; LiveLocation liveLocation = (LiveLocation) object;
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(liveLocation.marker.getPosition(), googleMap.getMaxZoomLevel() - 4)); final IMapController controller = mapView.getController();
controller.animateTo(liveLocation.marker.getPosition(), mapView.getMaxZoomLevel() -2 ,null);
} }
} }
}); });
@ -959,11 +981,6 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
mapView = new MapView(context) { mapView = new MapView(context) {
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {
MotionEvent eventToRecycle = null; MotionEvent eventToRecycle = null;
@ -979,7 +996,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
@Override @Override
public boolean onInterceptTouchEvent(MotionEvent ev) { public boolean onTouchEvent(MotionEvent ev) {
if (messageObject == null && chatLocation == null) { if (messageObject == null && chatLocation == null) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) { if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (animatorSet != null) { if (animatorSet != null) {
@ -1006,50 +1023,37 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
locationButton.setTag(Theme.key_location_actionIcon); locationButton.setTag(Theme.key_location_actionIcon);
userLocationMoved = true; userLocationMoved = true;
} }
if (googleMap != null) { if (mapView != null) {
if (userLocation != null) { if (userLocation != null) {
userLocation.setLatitude(googleMap.getCameraPosition().target.latitude); userLocation.setLatitude(mapView.getMapCenter().getLatitude());
userLocation.setLongitude(googleMap.getCameraPosition().target.longitude); userLocation.setLongitude(mapView.getMapCenter().getLongitude());
} }
} }
adapter.setCustomLocation(userLocation); adapter.setCustomLocation(userLocation);
} }
} }
return super.onInterceptTouchEvent(ev); return super.onTouchEvent(ev);
} }
}; };
final MapView map = mapView;
new Thread(() -> { AndroidUtilities.runOnUIThread(() -> {
try { if (mapView != null && getParentActivity() != null) {
map.onCreate(null); mapView.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10));
} catch (Exception e) { onMapInit();
//this will cause exception, but will preload google maps? mapsInitialized = true;
} if (isActiveThemeDark()) {
AndroidUtilities.runOnUIThread(() -> { /*currentMapStyleDark = true;
if (mapView != null && getParentActivity() != null) { MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(ApplicationLoader.applicationContext, R.raw.mapstyle_night);
try { googleMap.setMapStyle(style);
map.onCreate(null); */
MapsInitializer.initialize(ApplicationLoader.applicationContext); //TODO Dark?
mapView.getMapAsync(map1 -> {
googleMap = map1;
if (isActiveThemeDark()) {
currentMapStyleDark = true;
MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(ApplicationLoader.applicationContext, R.raw.mapstyle_night);
googleMap.setMapStyle(style);
}
googleMap.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10));
onMapInit();
});
mapsInitialized = true;
if (onResumeCalled) {
mapView.onResume();
}
} catch (Exception e) {
FileLog.e(e);
}
} }
}); if (onResumeCalled) {
}).start(); mapView.onResume();
}
}
});
if (messageObject == null && chatLocation == null) { if (messageObject == null && chatLocation == null) {
if (locationType == LOCATION_TYPE_GROUP && dialogId != 0) { if (locationType == LOCATION_TYPE_GROUP && dialogId != 0) {
@ -1200,6 +1204,16 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
animatorSet.start(); animatorSet.start();
} }
private TextView getAttributionOverlay(Context context) {
attributionOverlay = new TextView(context);
attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
attributionOverlay.setShadowLayer(1,-1,-1, Color.WHITE);
attributionOverlay.setLinksClickable(true);
attributionOverlay.setMovementMethod(LinkMovementMethod.getInstance());
return attributionOverlay;
}
private Bitmap createUserBitmap(LiveLocation liveLocation) { private Bitmap createUserBitmap(LiveLocation liveLocation) {
Bitmap result = null; Bitmap result = null;
try { try {
@ -1309,23 +1323,37 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
return; return;
} }
for (int a = 0, N = placeMarkers.size(); a < N; a++) { for (int a = 0, N = placeMarkers.size(); a < N; a++) {
placeMarkers.get(a).marker.remove(); placeMarkers.get(a).marker.remove(mapView);
} }
placeMarkers.clear(); placeMarkers.clear();
for (int a = 0, N = places.size(); a < N; a++) { for (int a = 0, N = places.size(); a < N; a++) {
TLRPC.TL_messageMediaVenue venue = places.get(a); TLRPC.TL_messageMediaVenue venue = places.get(a);
try { try {
MarkerOptions options = new MarkerOptions().position(new LatLng(venue.geo.lat, venue.geo._long)); Marker marker = new Marker(mapView);
options.icon(BitmapDescriptorFactory.fromBitmap(createPlaceBitmap(a))); marker.setPosition(new GeoPoint(venue.geo.lat, venue.geo._long));
options.anchor(0.5f, 0.5f); marker.setIcon(new BitmapDrawable(getParentActivity().getResources(), createPlaceBitmap(a)));
options.title(venue.title); marker.setAnchor(0.5f, 0.5f);
options.snippet(venue.address); mapView.getOverlays().add(marker);
marker.setTitle(venue.title);
marker.setSnippet(venue.address);
VenueLocation venueLocation = new VenueLocation(); VenueLocation venueLocation = new VenueLocation();
venueLocation.num = a; venueLocation.num = a;
venueLocation.marker = googleMap.addMarker(options); venueLocation.marker = marker;
venueLocation.venue = venue; venueLocation.venue = venue;
venueLocation.marker.setTag(venueLocation);
placeMarkers.add(venueLocation); placeMarkers.add(venueLocation);
marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker, MapView mapView) {
markerImageView.setVisibility(View.INVISIBLE);
if (!userLocationMoved) {
locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
locationButton.setTag(Theme.key_location_actionIcon);
userLocationMoved = true;
}
overlayView.addInfoView(marker, venueLocation);
return true;
}
});
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
@ -1334,7 +1362,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
private LiveLocation addUserMarker(TLRPC.Message message) { private LiveLocation addUserMarker(TLRPC.Message message) {
LiveLocation liveLocation; LiveLocation liveLocation;
LatLng latLng = new LatLng(message.media.geo.lat, message.media.geo._long); GeoPoint latLng = new GeoPoint(message.media.geo.lat, message.media.geo._long);
if ((liveLocation = markersMap.get(message.from_id)) == null) { if ((liveLocation = markersMap.get(message.from_id)) == null) {
liveLocation = new LiveLocation(); liveLocation = new LiveLocation();
liveLocation.object = message; liveLocation.object = message;
@ -1353,17 +1381,26 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
try { try {
MarkerOptions options = new MarkerOptions().position(latLng); Marker marker = new Marker(mapView);
marker.setPosition(latLng);
// InfoWindow workaround
marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker, MapView mapView) {
return false;
}
});
Bitmap bitmap = createUserBitmap(liveLocation); Bitmap bitmap = createUserBitmap(liveLocation);
if (bitmap != null) { if (bitmap != null) {
options.icon(BitmapDescriptorFactory.fromBitmap(bitmap)); marker.setIcon(new BitmapDrawable(getParentActivity().getResources(), bitmap));
options.anchor(0.5f, 0.907f); marker.setAnchor(0.5f, 0.907f);
liveLocation.marker = googleMap.addMarker(options); mapView.getOverlays().add(marker);
liveLocation.marker = marker;
markers.add(liveLocation); markers.add(liveLocation);
markersMap.put(liveLocation.id, liveLocation); markersMap.put(liveLocation.id, liveLocation);
LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId); LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId);
if (liveLocation.id == getUserConfig().getClientUserId() && myInfo != null && liveLocation.object.id == myInfo.mid && myLocation != null) { if (liveLocation.id == getUserConfig().getClientUserId() && myInfo != null && liveLocation.object.id == myInfo.mid && myLocation != null) {
liveLocation.marker.setPosition(new LatLng(myLocation.getLatitude(), myLocation.getLongitude())); liveLocation.marker.setPosition(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()));
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -1377,7 +1414,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
private LiveLocation addUserMarker(TLRPC.TL_channelLocation location) { private LiveLocation addUserMarker(TLRPC.TL_channelLocation location) {
LatLng latLng = new LatLng(location.geo_point.lat, location.geo_point._long); GeoPoint latLng = new GeoPoint(location.geo_point.lat, location.geo_point._long);
LiveLocation liveLocation = new LiveLocation(); LiveLocation liveLocation = new LiveLocation();
int did = (int) dialogId; int did = (int) dialogId;
if (did > 0) { if (did > 0) {
@ -1389,12 +1426,21 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
try { try {
MarkerOptions options = new MarkerOptions().position(latLng); Marker marker = new Marker(mapView);
marker.setPosition(latLng);
// InfoWindow workaround
marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker, MapView mapView) {
return false;
}
});
Bitmap bitmap = createUserBitmap(liveLocation); Bitmap bitmap = createUserBitmap(liveLocation);
if (bitmap != null) { if (bitmap != null) {
options.icon(BitmapDescriptorFactory.fromBitmap(bitmap)); marker.setIcon(new BitmapDrawable(getParentActivity().getResources(), bitmap));
options.anchor(0.5f, 0.907f); marker.setAnchor(0.5f, 0.907f);
liveLocation.marker = googleMap.addMarker(options); mapView.getOverlays().add(marker);
liveLocation.marker = marker;
markers.add(liveLocation); markers.add(liveLocation);
markersMap.put(liveLocation.id, liveLocation); markersMap.put(liveLocation.id, liveLocation);
} }
@ -1406,55 +1452,95 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
private void onMapInit() { private void onMapInit() {
if (googleMap == null) { if (mapView == null) {
return; return;
} }
//Paris, Tour Eiffel
GeoPoint initLocation = new GeoPoint(48.85825,2.29448);
final IMapController controller = mapView.getController();
mapView.setMaxZoomLevel(20.0);
mapView.setMultiTouchControls(true);
mapView.setBuiltInZoomControls(false);
controller.setCenter(initLocation);
controller.setZoom(7.);
if (chatLocation != null) { if (chatLocation != null) {
LiveLocation liveLocation = addUserMarker(chatLocation); LiveLocation liveLocation = addUserMarker(chatLocation);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(liveLocation.marker.getPosition(), googleMap.getMaxZoomLevel() - 4)); controller.setCenter(liveLocation.marker.getPosition());
controller.setZoom(mapView.getMaxZoomLevel() - 2);
} else if (messageObject != null) { } else if (messageObject != null) {
if (messageObject.isLiveLocation()) { if (messageObject.isLiveLocation()) {
LiveLocation liveLocation = addUserMarker(messageObject.messageOwner); LiveLocation liveLocation = addUserMarker(messageObject.messageOwner);
if (!getRecentLocations()) { if (!getRecentLocations()) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(liveLocation.marker.getPosition(), googleMap.getMaxZoomLevel() - 4)); controller.setCenter(liveLocation.marker.getPosition());
controller.setZoom(mapView.getMaxZoomLevel() - 2);
} }
} else { } else {
LatLng latLng = new LatLng(userLocation.getLatitude(), userLocation.getLongitude()); GeoPoint latLng = new GeoPoint(userLocation.getLatitude(), userLocation.getLongitude());
try { Marker marker = new Marker(mapView);
googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin2))); marker.setPosition(latLng);
} catch (Exception e) { // InfoWindow workaround
FileLog.e(e); marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker, MapView mapView) {
return false;
}
});
if (Build.VERSION.SDK_INT >= 21) {
marker.setIcon(getParentActivity().getDrawable(R.drawable.map_pin));
} else {
marker.setIcon(getParentActivity().getResources().getDrawable(R.drawable.map_pin2));
} }
CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 4); marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
googleMap.moveCamera(position); mapView.getOverlays().add(marker);
controller.setCenter(latLng);
controller.setZoom(mapView.getMaxZoomLevel() - 2);
firstFocus = false; firstFocus = false;
getRecentLocations(); getRecentLocations();
} }
} else { } else {
userLocation = new Location("network"); userLocation = new Location("network");
if (initialLocation != null) { if (initialLocation != null) {
LatLng latLng = new LatLng(initialLocation.geo_point.lat, initialLocation.geo_point._long); GeoPoint latLng = new GeoPoint(initialLocation.geo_point.lat, initialLocation.geo_point._long);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 4)); controller.setCenter(latLng);
controller.setZoom(mapView.getMaxZoomLevel() - 2);
userLocation.setLatitude(initialLocation.geo_point.lat); userLocation.setLatitude(initialLocation.geo_point.lat);
userLocation.setLongitude(initialLocation.geo_point._long); userLocation.setLongitude(initialLocation.geo_point._long);
adapter.setCustomLocation(userLocation); adapter.setCustomLocation(userLocation);
} else { } else {
userLocation.setLatitude(20.659322); userLocation.setLatitude(48.85825);
userLocation.setLongitude(-11.406250); userLocation.setLongitude(2.29448);
} }
} }
try { GpsMyLocationProvider imlp = new GpsMyLocationProvider(getParentActivity());
googleMap.setMyLocationEnabled(true); imlp.setLocationUpdateMinDistance(10);
} catch (Exception e) { imlp.setLocationUpdateMinTime(10000);
FileLog.e(e); imlp.addLocationSource(LocationManager.NETWORK_PROVIDER);
} myLocationOverlay = new MyLocationNewOverlay(imlp, mapView) {
googleMap.getUiSettings().setMyLocationButtonEnabled(false); @Override
googleMap.getUiSettings().setZoomControlsEnabled(false); public void onLocationChanged(final Location location, IMyLocationProvider source) {
googleMap.getUiSettings().setCompassEnabled(false); super.onLocationChanged(location, source);
googleMap.setOnCameraMoveStartedListener(reason -> { if (location != null) {
if (reason == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) { AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
positionMarker(location);
LocationController.getInstance(currentAccount).setGoogleMapLocation(location, isFirstLocation);
isFirstLocation = false;
}
});
}
}
};
myLocationOverlay.enableMyLocation();
myLocationOverlay.setDrawAccuracyEnabled(true);
//TODO
mapView.addMapListener(new MapListener() {
@Override
public boolean onScroll(ScrollEvent event) {
showSearchPlacesButton(true); showSearchPlacesButton(true);
removeInfoView(); removeInfoView();
@ -1466,40 +1552,49 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
int min = locationType == LOCATION_TYPE_SEND ? 0 : AndroidUtilities.dp(66); int min = locationType == LOCATION_TYPE_SEND ? 0 : AndroidUtilities.dp(66);
int top = view.getTop(); int top = view.getTop();
if (top < -min) { if (top < -min) {
CameraPosition cameraPosition = googleMap.getCameraPosition(); forceUpdate = mapView.getMapCenter(); //TODO. Strange variable
forceUpdate = CameraUpdateFactory.newLatLngZoom(cameraPosition.target, cameraPosition.zoom);
listView.smoothScrollBy(0, top + min); listView.smoothScrollBy(0, top + min);
} }
} }
} }
} }
return false;
}
@Override
public boolean onZoom(ZoomEvent event) {
return false;
} }
}); });
googleMap.setOnMyLocationChangeListener(location -> { myLocationOverlay.runOnFirstFix(new Runnable() {
positionMarker(location); public void run() {
getLocationController().setGoogleMapLocation(location, isFirstLocation); AndroidUtilities.runOnUIThread(new Runnable() {
isFirstLocation = false; @Override
}); public void run() {
googleMap.setOnMarkerClickListener(marker -> { positionMarker(myLocationOverlay.getLastFix());
if (!(marker.getTag() instanceof VenueLocation)) { getLocationController().getInstance(currentAccount).setGoogleMapLocation(myLocationOverlay.getLastFix(), isFirstLocation);
return true; isFirstLocation = false;
}
});
} }
markerImageView.setVisibility(View.INVISIBLE);
if (!userLocationMoved) {
locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
locationButton.setTag(Theme.key_location_actionIcon);
userLocationMoved = true;
}
overlayView.addInfoView(marker);
return true;
}); });
googleMap.setOnCameraMoveListener(() -> { mapView.getOverlays().add(myLocationOverlay);
if (overlayView != null) { mapView.addMapListener(new MapListener() {
overlayView.updatePositions(); @Override
public boolean onScroll(ScrollEvent event) {
if (overlayView != null) {
overlayView.updatePositions();
}
return false;
}
@Override
public boolean onZoom(ZoomEvent event) {
return false;
} }
}); });
positionMarker(myLocation = getLastLocation()); positionMarker(myLocation = getLastLocation());
attributionOverlay.bringToFront();
if (checkGpsEnabled && getParentActivity() != null) { if (checkGpsEnabled && getParentActivity() != null) {
checkGpsEnabled = false; checkGpsEnabled = false;
if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) { if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
@ -1660,8 +1755,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
layoutParams = (FrameLayout.LayoutParams) mapView.getLayoutParams(); layoutParams = (FrameLayout.LayoutParams) mapView.getLayoutParams();
if (layoutParams != null && layoutParams.height != overScrollHeight + AndroidUtilities.dp(10)) { if (layoutParams != null && layoutParams.height != overScrollHeight + AndroidUtilities.dp(10)) {
layoutParams.height = overScrollHeight + AndroidUtilities.dp(10); layoutParams.height = overScrollHeight + AndroidUtilities.dp(10);
if (googleMap != null) { if (mapView != null) {
googleMap.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10)); mapView.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10));
} }
mapView.setLayoutParams(layoutParams); mapView.setLayoutParams(layoutParams);
} }
@ -1705,8 +1800,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
layoutParams = (FrameLayout.LayoutParams) mapView.getLayoutParams(); layoutParams = (FrameLayout.LayoutParams) mapView.getLayoutParams();
if (layoutParams != null) { if (layoutParams != null) {
layoutParams.height = overScrollHeight + AndroidUtilities.dp(10); layoutParams.height = overScrollHeight + AndroidUtilities.dp(10);
if (googleMap != null) { if (mapView != null) {
googleMap.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10)); mapView.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10));
} }
mapView.setLayoutParams(layoutParams); mapView.setLayoutParams(layoutParams);
} }
@ -1741,16 +1836,20 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
private Location getLastLocation() { private Location getLastLocation() {
LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE); if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && getParentActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
List<String> providers = lm.getProviders(true); return null;
Location l = null; } else {
for (int i = providers.size() - 1; i >= 0; i--) { LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE);
l = lm.getLastKnownLocation(providers.get(i)); List<String> providers = lm.getProviders(true);
if (l != null) { Location l = null;
break; for (int i = providers.size() - 1; i >= 0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) {
break;
}
} }
return l;
} }
return l;
} }
private void positionMarker(Location location) { private void positionMarker(Location location) {
@ -1761,10 +1860,10 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
LiveLocation liveLocation = markersMap.get(getUserConfig().getClientUserId()); LiveLocation liveLocation = markersMap.get(getUserConfig().getClientUserId());
LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId); LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId);
if (liveLocation != null && myInfo != null && liveLocation.object.id == myInfo.mid) { if (liveLocation != null && myInfo != null && liveLocation.object.id == myInfo.mid) {
liveLocation.marker.setPosition(new LatLng(location.getLatitude(), location.getLongitude())); liveLocation.marker.setPosition(new GeoPoint(location.getLatitude(), location.getLongitude()));
} }
if (messageObject == null && chatLocation == null && googleMap != null) { if (messageObject == null && chatLocation == null && mapView != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); GeoPoint latLng = new GeoPoint(location.getLatitude(), location.getLongitude());
if (adapter != null) { if (adapter != null) {
if (!searchedForCustomLocations && locationType != LOCATION_TYPE_GROUP) { if (!searchedForCustomLocations && locationType != LOCATION_TYPE_GROUP) {
adapter.searchPlacesWithQuery(null, myLocation, true); adapter.searchPlacesWithQuery(null, myLocation, true);
@ -1774,12 +1873,13 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
if (!userLocationMoved) { if (!userLocationMoved) {
userLocation = new Location(location); userLocation = new Location(location);
if (firstWas) { if (firstWas) {
CameraUpdate position = CameraUpdateFactory.newLatLng(latLng); final IMapController controller = mapView.getController();
googleMap.animateCamera(position); controller.animateTo(latLng);
} else { } else {
firstWas = true; firstWas = true;
CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 4); final IMapController controller = mapView.getController();
googleMap.moveCamera(position); controller.setZoom(mapView.getMaxZoomLevel() - 2);
controller.setCenter(latLng);
} }
} }
} else { } else {
@ -1807,10 +1907,10 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
private static final double EARTHRADIUS = 6366198; private static final double EARTHRADIUS = 6366198;
private static LatLng move(LatLng startLL, double toNorth, double toEast) { private static GeoPoint move(GeoPoint startLL, double toNorth, double toEast) {
double lonDiff = meterToLongitude(toEast, startLL.latitude); double lonDiff = meterToLongitude(toEast, startLL.getLatitude());
double latDiff = meterToLatitude(toNorth); double latDiff = meterToLatitude(toNorth);
return new LatLng(startLL.latitude + latDiff, startLL.longitude + lonDiff); return new GeoPoint(startLL.getLatitude() + latDiff, startLL.getLongitude() + lonDiff);
} }
private static double meterToLongitude(double meterToEast, double latitude) { private static double meterToLongitude(double meterToEast, double latitude) {
@ -1827,36 +1927,43 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
private void fetchRecentLocations(ArrayList<TLRPC.Message> messages) { private void fetchRecentLocations(ArrayList<TLRPC.Message> messages) {
LatLngBounds.Builder builder = null; BoundingBox builder = null;
List<GeoPoint> GeoPoints = new ArrayList<>();
if (firstFocus) { if (firstFocus) {
builder = new LatLngBounds.Builder(); builder = null;
} }
int date = getConnectionsManager().getCurrentTime(); int date = getConnectionsManager().getCurrentTime();
for (int a = 0; a < messages.size(); a++) { for (int a = 0; a < messages.size(); a++) {
TLRPC.Message message = messages.get(a); TLRPC.Message message = messages.get(a);
if (message.date + message.media.period > date) { if (message.date + message.media.period > date) {
if (builder != null) { if (builder != null) {
LatLng latLng = new LatLng(message.media.geo.lat, message.media.geo._long); GeoPoint latLng = new GeoPoint(message.media.geo.lat, message.media.geo._long);
builder.include(latLng); GeoPoints.add(latLng);
} }
addUserMarker(message); addUserMarker(message);
} }
} }
if (builder != null) { if (GeoPoints.size()>0) {
builder = BoundingBox.fromGeoPoints(GeoPoints);
}
if (firstFocus) {
firstFocus = false; firstFocus = false;
adapter.setLiveLocations(markers); adapter.setLiveLocations(markers);
if (messageObject.isLiveLocation()) { if (messageObject.isLiveLocation()) {
try { try {
LatLngBounds bounds = builder.build(); BoundingBox bounds = builder;
LatLng center = bounds.getCenter(); GeoPoint center = bounds.getCenterWithDateLine(); //TODO check
LatLng northEast = move(center, 100, 100); GeoPoint northEast = move(center, 100, 100);
LatLng southWest = move(center, -100, -100); GeoPoint southWest = move(center, -100, -100);
builder.include(southWest); GeoPoints.add(southWest);
builder.include(northEast); GeoPoints.add(northEast);
bounds = builder.build(); if (GeoPoints.size()>0) {
builder = BoundingBox.fromGeoPoints(GeoPoints);
}
bounds = builder;
if (messages.size() > 1) { if (messages.size() > 1) {
try { try {
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, AndroidUtilities.dp(60))); mapView.zoomToBoundingBox(bounds, false,AndroidUtilities.dp(60));
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
@ -1889,7 +1996,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
getConnectionsManager().sendRequest(req, (response, error) -> { getConnectionsManager().sendRequest(req, (response, error) -> {
if (response != null) { if (response != null) {
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
if (googleMap == null) { if (mapView == null) {
return; return;
} }
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
@ -1928,12 +2035,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
if (id == NotificationCenter.closeChats) { if (id == NotificationCenter.closeChats) {
removeSelfFromStack(); removeSelfFromStack();
} else if (id == NotificationCenter.locationPermissionGranted) { } else if (id == NotificationCenter.locationPermissionGranted) {
if (googleMap != null) { if (mapView != null && mapsInitialized) {
try { myLocationOverlay.enableMyLocation();
googleMap.setMyLocationEnabled(true);
} catch (Exception e) {
FileLog.e(e);
}
} }
} else if (id == NotificationCenter.didReceiveNewMessages) { } else if (id == NotificationCenter.didReceiveNewMessages) {
boolean scheduled = (Boolean) args[2]; boolean scheduled = (Boolean) args[2];
@ -1973,7 +2076,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(did); LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(did);
if (myInfo == null || myInfo.mid != messageObject.getId()) { if (myInfo == null || myInfo.mid != messageObject.getId()) {
liveLocation.object = messageObject.messageOwner; liveLocation.object = messageObject.messageOwner;
liveLocation.marker.setPosition(new LatLng(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long)); liveLocation.marker.setPosition(new GeoPoint(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long));
} }
updated = true; updated = true;
} }
@ -1993,6 +2096,10 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
if(mapView.getOverlays().contains(myLocationOverlay)) {
mapView.getOverlays().remove(myLocationOverlay);
}
myLocationOverlay.disableMyLocation();
} }
onResumeCalled = false; onResumeCalled = false;
} }
@ -2005,18 +2112,13 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
if (mapView != null && mapsInitialized) { if (mapView != null && mapsInitialized) {
try { try {
mapView.onResume(); mapView.onResume();
} catch (Throwable e) {
FileLog.e(e);
}
}
onResumeCalled = true;
if (googleMap != null) {
try {
googleMap.setMyLocationEnabled(true);
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
} }
onResumeCalled = true;
fixLayoutInternal(true); fixLayoutInternal(true);
if (checkPermission && Build.VERSION.SDK_INT >= 23) { if (checkPermission && Build.VERSION.SDK_INT >= 23) {
Activity activity = getParentActivity(); Activity activity = getParentActivity();
@ -2033,14 +2135,6 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
} }
} }
@Override
public void onLowMemory() {
super.onLowMemory();
if (mapView != null && mapsInitialized) {
mapView.onLowMemory();
}
}
public void setDelegate(LocationActivityDelegate delegate) { public void setDelegate(LocationActivityDelegate delegate) {
this.delegate = delegate; this.delegate = delegate;
} }
@ -2068,17 +2162,16 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY));
shadow.invalidate(); shadow.invalidate();
if (googleMap != null) { if (mapView != null) {
if (isActiveThemeDark()) { if (isActiveThemeDark()) {
if (!currentMapStyleDark) { if (!currentMapStyleDark) {
currentMapStyleDark = true; currentMapStyleDark = true;
MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(ApplicationLoader.applicationContext, R.raw.mapstyle_night); // TODO dark
googleMap.setMapStyle(style);
} }
} else { } else {
if (currentMapStyleDark) { if (currentMapStyleDark) {
currentMapStyleDark = false; currentMapStyleDark = false;
googleMap.setMapStyle(null); // TODO dark
} }
} }
} }

View File

@ -7,7 +7,6 @@ buildscript {
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:4.0.0' classpath 'com.android.tools.build:gradle:4.0.0'
classpath 'com.google.gms:google-services:4.3.3'
} }
} }
repositories { repositories {