在谷歌地图android中添加和保存标记 [英] Adding and saving marker in Google maps android

查看:88
本文介绍了在谷歌地图android中添加和保存标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我是Android的新手,我想制作一个可以获取我的设备(手机)位置的应用程序,并且在我的自定义地图上它应该是显示一个标记(就像它在我们打开官方谷歌地图时显示我的位置)并在退出/重新启动应用程序后,它应该保存我在地图上的最后一个(访问过的)位置标记。



我已附上我的代码

它做什么:它将获得设备的位置(

纬度和经度

)并将标记放在自定义的Google地图上。





如果它没有保存我的标记/位置地图



请帮助



我尝试了什么:



我在Android Studio中的代码

< pre>公共类MapActivity扩展AppCompatActivity实现OnMapReadyCallback {
private static final String TAG =MapActivity;
私人GoogleMap mMap;
LocationManager locationManager;
DatabaseHelper myDB;

private FusedLocationProviderClient mFusedLocationProviderClient;
private Boolean mLocationPermissionGranted = false;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final String FINE_LOCATION = android.Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = android.Manifest.permission.ACCESS_COARSE_LOCATION;
private static final float DEFAULT_ZOOM = 15f;


@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getLocationPermission();
}

private void getLocationPermission()
{
Log.d(TAG,getLocationPermission:获取位置权限);
String [] permission = {android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION};

if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),COARSE_LOCATION)== PackageManager .PERMISSION_GRANTED){
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this,permission,LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,permission,LOCATION_PERMISSION_REQUEST_CODE);
}
}

private void initMap(){
Log.d(TAG,initMap:initilizing map);
SupportMapFragment mapFragment =(SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}

@Override
public void onMapReady(GoogleMap googleMap){
Toast.makeText(this,Map is Ready,Toast.LENGTH_SHORT).show( );
Log.d(TAG,onMapReady:Map is Ready);
mMap = googleMap;
if(mLocationPermissionGranted){
getDeviceLocation();
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED&& ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION )!= PackageManager.PERMISSION_GRANTED){
return;
}
mMap.setMyLocationEnabled(true);
}

}

private void getDeviceLocation(){
Log.d(TAG,getDeviceLocation:获取设备当前位置);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if(mLocationPermissionGranted){
任务位置= mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener(){
@Override
public void onComplete(@NonNull Task task){
if(task.isSuccessful()){
Log.d(TAG,onComplete:Found location);
Location currentLocation =(Location)task.getResult();
if(currentLocation!= null)
{

moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),
DEFAULT_ZOOM,Updated);

}
}
else
{
Log.d(TAG,onComplete:当前位置为空);
Toast.makeText(MapActivity.this,无法获取当前位置 ,Toast.LENGTH_SHORT).show();
}
}
});
}
} catch(SecurityException e){
Log.e(TAG,getDeviceLocation:SecurityException+ e.getMessage());
}
}

private void moveCamera(LatLng latLng,float zoom,String title)
{
Log.d(TAG,moveCamera:Moving相机到纬度:+ latLng.latitude +,经度:+ latLng.longitude;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));
MarkerOptions options = new MarkerOptions()。position(latLng).title(title);
mMap.addMarker(期权);
HideSoftKeyboard();
}


private void HideSoftKeyboard()
{
this.getWindow()。setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}

解决方案

将活动的坐标保存在 onStop()方法。在活动的 onCreate()方法中,它应检查以前保存的坐标的 savedInstanceState 参数。



根据您应用的设计,您可能必须使用 onSaveInstanceState() onRestoreInstanceState()而不是。


这是我的解决方案

活动类





 private void getLocationFromDataBase(){
DatabaseHelper myDB = new DatabaseHelper(this);
列表< LatLng> lls = myDB.getAllLATLNG();

for(LatLng ll:lls){
LatLng coordinate = new LatLng(ll.latitude,ll.longitude);
Marker marker = mMap.addMarker(new MarkerOptions()。position(coordinate).title(Marker in loop));
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
Toast.makeText(this,lat+ String.valueOf(ll.latitude)+;;+ String.valueOf(ll.longitude),Toast.LENGTH_SHORT)。show();

}
}







数据库助手班



公开名单< LatLng> getAllLATLNG(){
SQLiteDatabase db = this.getReadableDatabase();
列表< LatLng> latLngList = new ArrayList< LatLng>();
字符串selectQuery =SELECT * FROM+ TABLE_NAME +其中LATITUDE不为空;

Cursor cursor = db.rawQuery(selectQuery,null);

//循环遍历所有行并添加到列表
if(cursor.moveToFirst())
{
do
{
double的x,y;
x = Double.parseDouble(cursor.getString(4));
y = Double.parseDouble(cursor.getString(5));
LatLng ll = new LatLng(x,y);
//添加联系人列表
latLngList.add(ll);
} while(cursor.moveToNext());

}
返回latLngList;
}


要显示地图,请使用Google Maps Android API将片段添加到您的活动中,如下所示。 

将Fragment元素添加到活动的布局文件名isactivity_maps.xml中。此元素定义一个SupportMapFragment,用作地图的容器并提供对GoogleMap对象的访问。这将有助于Android支持库版本的地图片段,以确保与早期版本的Android框架向后兼容。
在activity的oncreate()方法中设置文件的布局。


Hello everyone,

I am new to android and I want to make an app that get my device (mobile phone) location and on my custom map it should show a marker (just like it shows my location when we open official google map) and after exiting/restarting the app it should save my last (visited) location marker on the map itself.

I have attached my code
What it does : it will get the location of the device(

Latitude and Longitude

) and put marker on the custom Google Map.

But
when it does not save my marker/location the map

Please Assist

What I have tried:

My Code so far in Android Studio

<pre>public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
    private static final String TAG = "MapActivity";
    private GoogleMap mMap;
    LocationManager locationManager;
    DatabaseHelper myDB;

    private FusedLocationProviderClient mFusedLocationProviderClient;
    private Boolean mLocationPermissionGranted = false;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final String FINE_LOCATION = android.Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = android.Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final float DEFAULT_ZOOM = 15f;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        getLocationPermission();
    }

    private void getLocationPermission()
    {
        Log.d(TAG, "getLocationPermission: getting location permission");
        String[] permission = {android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION};

        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
                initMap();
            } else {
                ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUEST_CODE);
            }
        } else {
            ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    private void initMap() {
        Log.d(TAG, "initMap: initilizing map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(MapActivity.this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onMapReady: Map is Ready");
        mMap = googleMap;
        if (mLocationPermissionGranted) {
            getDeviceLocation();
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mMap.setMyLocationEnabled(true);
        }

    }

    private void getDeviceLocation() {
        Log.d(TAG, "getDeviceLocation: getting the device current location");
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        try {
            if (mLocationPermissionGranted) {
                Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "onComplete: Found location");
                            Location currentLocation = (Location)task.getResult();
                            if(currentLocation !=null)
                             {

                             moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),
                             DEFAULT_ZOOM,"Updated");

                             }
                        }
                        else
                        {
                            Log.d(TAG, "onComplete: Current location is null");
                            Toast.makeText(MapActivity.this, " unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        } catch (SecurityException e) {
            Log.e(TAG, "getDeviceLocation: SecurityException" + e.getMessage());
        }
    }

    private void moveCamera(LatLng latLng, float zoom, String title)
    {
        Log.d(TAG, "moveCamera:  Moving camera to Latitude: "+latLng.latitude + ", Longitude :"+latLng.longitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
        MarkerOptions options = new MarkerOptions().position(latLng).title(title);
        mMap.addMarker(options);
        HideSoftKeyboard();
    }


    private void HideSoftKeyboard()
    {
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

解决方案

Save the coordinates in the activity's onStop() method. In the activity's onCreate() method, it should check the savedInstanceState parameter for previously saved coordinates.

Depending on your app's design, you may have to use onSaveInstanceState() and onRestoreInstanceState() instead.


here is my solution
Activity class


private void getLocationFromDataBase() {
       DatabaseHelper myDB = new DatabaseHelper(this);
       List<LatLng> lls = myDB.getAllLATLNG();

       for (LatLng ll : lls) {
           LatLng coordinate = new LatLng(ll.latitude, ll.longitude);
           Marker marker = mMap.addMarker(new MarkerOptions().position(coordinate).title("Marker in loop"));
           marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
           Toast.makeText(this, "lat " + String.valueOf(ll.latitude) + " ;; " + String.valueOf(ll.longitude), Toast.LENGTH_SHORT).show();

       }
   }




Database Helper class

public List<LatLng> getAllLATLNG() {
        SQLiteDatabase db = this.getReadableDatabase();
        List<LatLng>  latLngList = new ArrayList<LatLng>();
        String selectQuery = "SELECT  * FROM " + TABLE_NAME +" where LATITUDE is not null";

        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst())
        {
            do
            {
                 double x,y;
                 x = Double.parseDouble(cursor.getString(4));
                 y = Double.parseDouble(cursor.getString(5));
                 LatLng ll= new LatLng(x,y);
                // Adding contact to list
                 latLngList.add(ll);
            }while(cursor.moveToNext());

        }
        return latLngList;
    }


 To Display a map, using the Google Maps Android API you have to add fragments to your activity like this.

Add a Fragment element to your activity's layout file name isactivity_maps.xml. This element defines a SupportMapFragment to act as a container for the map and to provide access to the GoogleMap object. The will help the Android support library version of the map fragment, to ensure backward compatibility with earlier versions of the Android framework.
In activity's oncreate() method set layouts of your file. 


这篇关于在谷歌地图android中添加和保存标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆