在async-task onPostExecution之后在当前位置绘制一个标记 [英] Plot a marker on current location after async-task onPostExecution

查看:180
本文介绍了在async-task onPostExecution之后在当前位置绘制一个标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,使用AsyncTask绘制标记。我试图在onPostExeution()上标记当前位置的标记,并将我的相机移动到当前位置。我尝试了很多方法来实现这一点,但不幸的是应用程序崩溃。所以,您可以引导我在当前位置绘制标记并移动我的一旦我在onPostExecute()中收到位置更新,相机就会进入该位置。

这是我的代码 -



MainActivity.java

  public class MainActivity extends AppCompatActivity 
实现NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {

SupportMapFragment sMapFragment;
public GoogleMap mMap;
私有HttpURLConnection urlConnection = null;
private BufferedReader reader = null;
private String forecastJsonStr = null;
private String url =my_url;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
工具栏工具栏=(工具栏)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sMapFragment = SupportMapFragment.newInstance();


DrawerLayout drawer =(DrawerLayout)findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView =(NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
sMapFragment.getMapAsync(this);
android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
sFM.beginTransaction()。add(R.id.Map,sMapFragment).commit();



//搜索选项
$ b $ public void onMapSearch(View view)throws IOException {

// hide当按下按钮时按钮
InputMethodManager inputManager =(InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus()。getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

//将输入的地址预览为Tost in bar
EditText locationSearch =(EditText)findViewById(R.id.editText);
String location = locationSearch.getText()。toString();

//这将为相机设置动画并缩放12.0f
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));


//更多地址搜索代码
列表<地址> addressList = null;

//如果在编辑文本中不输入任何内容,则不会显示敬酒而不是崩溃的应用程序
if(locationSearch.getText()。toString()。equals( )){
Toast.makeText(this,请输入一个地址,Toast.LENGTH_LONG).show();
} else {

//处理异常并查找位置
if(location!= null ||!location.equals()){
Geocoder geocoder =新的地理编码器(this);
尝试{
addressList = geocoder.getFromLocationName(location,1);
} catch(IOException e){
e.printStackTrace();
}
//如果地址大于1,那么这些进程将会发生

if(addressList.size()> 0){
Address address = addressList获得(0);
LatLng latLng = new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(location +is Here)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE) ));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

Toast.makeText(this,位置+在这里,放大或缩小以使您的Thekha可见,Toast.LENGTH_LONG)
.show(); //弹出类型显示输入的数据
} else {
//输入条目将不会找到的进程,这将显示弹出

Toast.makeText(这是输入的地址未找到,Toast.LENGTH_LONG).show();






$ b //异步任务

ProgressDialog pd = null;

私有类RetriveMarkerTask扩展AsyncTask< String,Void,String> {
私人上下文上下文;


public RetriveMarkerTask(Context context){
this.context = context;
}

@Override
保护void onPreExecute(){
pd = new ProgressDialog(MainActivity.this);
pd.setTitle(Please wait ...);
pd.setMessage(连接到Loofre网络);
pd.setCancelable(false);
pd.show();



保护字符串doInBackground(String ... markerGetUrl){
try {
//构造OpenWeatherMap查询的URL
//可能的参数可以在OWM的预测API页面获得,位于
// http://openweathermap.org/API#forecast
URL url1 =新的URL(url);

//创建OpenWeatherMap的请求,并打开连接
urlConnection =(HttpURLConnection)url1.openConnection();
urlConnection.setRequestMethod(GET);
urlConnection.connect();

//将输入流读入字符串
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream == null){
//无事可做。
返回null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));

字符串行;
while((line = reader.readLine())!= null){
//因为是JSON,所以不需要添加换行符(它不会影响解析)
/ /但是,如果打印出完整的
//缓冲区以进行调试,它确实使调试变得更加容易。
buffer.append(line +\\\
);
}

if(buffer.length()== 0){
// Stream是空的。解析没有意义。
返回null;
}
forecastJsonStr = buffer.toString();
} catch(IOException e){
Log.e(PlaceholderFragment,Error,e);
//如果代码没有成功获取天气数据,则尝试
//来解析它没有意义。
forecastJsonStr =错误,引发异常。;
} finally {
if(urlConnection!= null){
urlConnection.disconnect();

if(reader!= null){
try {
reader.close();
catch(final IOException e){
Log.e(PlaceholderFragment,Error closing stream,e);
}
}
}
返回forecastJsonStr;

}

//执行后
$ b $保护无效onPostExecute(字符串标记){


Log.d(字符串响应,标记);

Toast.makeText(MainActivity.this,绘制Thekha,Toast.LENGTH_LONG).show();

尝试{
JSONArray jsonArray = new JSONArray(markers);
for(int i = 0; i< jsonArray.length(); i ++){
//创建json数据中每个位置的标记
JSONObject jsonObject = jsonArray.getJSONObject(i );
String placeName = jsonObject.getString(name);
String placeAddress = jsonObject.getString(address);
double latitude = jsonObject.getJSONArray(latlang)。getDouble(0);
double longitude = jsonObject.getJSONArray(latlang)。getDouble(1);
LatLng loc =新LatLng(经度,纬度);
//标记大小更改代码
int height = 150;
int width = 150;
BitmapDrawable bitmapDrawable =(BitmapDrawable)getResources()。getDrawable(R.drawable.thekhaicon);
位图b = bitmapDrawable.getBitmap();
位图smallMarker = Bitmap.createScaledBitmap(b,width,height,false);
//标记大小更改代码在此处结束
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc,13));

mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
.title(placeName)
.snippet(placeAddress)
.position(loc)

);

LatLng dwarka =新LatLng(28.570317,77.32182);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dwarka,13));
mMap.addMarker(
新MarkerOptions()
.title(诺伊达18区葡萄酒啤酒酒铺)
.snippet(Sector 18,Near Centre Stage Mall ,诺伊达)
.position(dwarka));
}
pd.dismiss();
} catch(JSONException e){
e.printStackTrace();
}

}
}







@Override
public void onBackPressed(){
DrawerLayout drawer =(DrawerLayout)findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();



@Override
public boolean onCreateOptionsMenu(菜单菜单){
//使菜单膨胀;这会将项目添加到操作栏(如果存在)。
getMenuInflater()。inflate(R.menu.main,menu);
返回true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
// Handle action bar item clicks here here。操作栏将
//自动处理Home / Up按钮上的点击,只要您在AndroidManifest.xml中指定了一个父活动,就可以长按
//。
int id = item.getItemId();

// noinspection SimplifiableIfStatement
if(id == R.id.action_settings){
return true;
}

返回super.onOptionsItemSelected(item);

$ b @SuppressWarnings(StatementWithEmptyBody)
@Override
public boolean onNavigationItemSelected(MenuItem item){
// Handle navigation view item clicks here 。
int id = item.getItemId();

if(id == R.id.nav_camera){
//处理相机动作
}否则if(id == R.id.nav_gallery){

} else if(id == R.id.nav_slideshow){

} else if(id == R.id.nav_manage){

}其他if(id == R.id.call_us){
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(tel:+919717001947));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在此请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String [] permissions,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
返回true;
}
startActivity(intent);

} else if(id == R.id.about_us){
Intent intent = new Intent(this,ScrollingActivity.class);
this.startActivity(intent);

}

DrawerLayout drawer =(DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
返回true;

$ b @Override
public void onMapReady(GoogleMap googleMap){
Toast.makeText(this,Connecting Server,Toast.LENGTH_LONG).show() ;
mMap = googleMap;

尝试{
RetriveMarkerTask markerTask = new RetriveMarkerTask(MainActivity.this);
markerTask.execute(url);
} catch(Exception e){
Toast.makeText(this,Can not fetch data,Toast.LENGTH_LONG).show();

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){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在这里请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String [] permissions,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
}
//工具栏和其他与map相关的工具uiSettings
// mMap.setMyLocationEnabled(true);
mMap.getUiSettings()。setZoomControlsEnabled(true);
mMap.getUiSettings()。setMapToolbarEnabled(true);
mMap.getUiSettings()。setMyLocationButtonEnabled(true);


我的manifest.xml文件 -



 <! -  
ACCESS_COARSE / FINE_LOCATION权限不是必需的要使用
Google Maps Android API v2,但您必须为MyLocation功能指定粗略或精细的
位置权限。
- >
< uses-permission android:name =android.permission.CALL_PHONE/>
< uses-permission android:name =android.permission.INTERNET/>
< uses-permission android:name =android.permission.ACCESS_NETWORK_STATE/>
< uses-permission android:name =android.permission.WRITE_EXTERNAL_STORAGE/>
<使用权限android:name =com.google.android.providers.gsf.permission.READ_GSWEVICES/>
< uses-permission android:name =android.permission.ACCESS_COARSE_LOCATION/>
< uses-permission android:name =android.permission.ACCESS_FINE_LOCATION/>

< application
android:name =android.support.multidex.MultiDexApplication
android:allowBackup =true
android:icon =@ mipmap / ic_launcher
android:label =Thekha
android:supportsRtl =true
android:theme =@ style / AppTheme>
< activity
android:name =。MainActivity
android:label =@ string / app_name
android:theme =@ style / AppTheme.NoActionBar> ;< /活性GT;
<! -
Google Maps API API密钥定义为字符串资源。
(请参阅文件res / values / google_maps_api.xml)。
请注意,API密钥已链接到用于签署APK的加密密钥。
您需要为每个加密密钥使用不同的API密钥,包括用于
签名的发布密钥。
您可以在src / debug /和src / release /中定义调试和发布目标的键。
- >
< meta-data
android:name =com.google.android.geo.API_KEY
android:value =AIzaSyAma5WZ9H5yskkt3AsQwc3aeQOFCyc9aGo/>

< activity android:name =。LoginActivity>
< intent-filter>

< category android:name =android.intent.category.LAUNCHER/>
< / intent-filter>
< / activity>
android:name =。ScrollingActivity
android:label =@ string / title_activity_scrolling
android:theme =@ style / AppTheme.NoActionBar> ;< /活性GT;
< / application>


解决方案


  public class MainActivity extends AppCompatActivity 
实现NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {

SupportMapFragment sMapFragment;
public GoogleMap mMap;
私有HttpURLConnection urlConnection = null;
private BufferedReader reader = null;
private String forecastJsonStr = null;
private String url =my_url;

@Override

protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
工具栏工具栏=(工具栏)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sMapFragment = SupportMapFragment.newInstance();


DrawerLayout drawer =(DrawerLayout)findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView =(NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
sMapFragment.getMapAsync(this);
android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
sFM.beginTransaction()。add(R.id.Map,sMapFragment).commit();



//搜索选项
$ b $ public void onMapSearch(View view)throws IOException {

// hide当按下按钮时按钮
InputMethodManager inputManager =(InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus()。getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

//将输入的地址预览为Tost in bar
EditText locationSearch =(EditText)findViewById(R.id.editText);
String location = locationSearch.getText()。toString();

//这将为相机设置动画并缩放12.0f
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));


//更多地址搜索代码
列表<地址> addressList = null;

//如果在编辑文本中不输入任何内容,则不会显示敬酒而不是崩溃的应用程序
if(locationSearch.getText()。toString()。equals( )){
Toast.makeText(this,请输入一个地址,Toast.LENGTH_LONG).show();
} else {

//处理异常并查找位置
if(location!= null ||!location.equals()){
Geocoder geocoder =新的地理编码器(this);
尝试{
addressList = geocoder.getFromLocationName(location,1);
} catch(IOException e){
e.printStackTrace();
}
//如果地址大于1,那么这些进程将会发生

if(addressList.size()> 0){
Address address = addressList获得(0);
LatLng latLng = new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(location +is Here)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE) ));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

Toast.makeText(this,位置+在这里,放大或缩小以使您的Thekha可见,Toast.LENGTH_LONG)
.show(); //弹出类型显示输入的数据
} else {
//输入条目将不会找到的进程,这将显示弹出

Toast.makeText(这是输入的地址未找到,Toast.LENGTH_LONG).show();






$ b //异步任务

ProgressDialog pd = null;

私有类RetriveMarkerTask扩展AsyncTask< String,Void,String> {
私人上下文上下文;


public RetriveMarkerTask(Context context){
this.context = context;
}

@Override
保护void onPreExecute(){
pd = new ProgressDialog(MainActivity.this);
pd.setTitle(Please wait ...);
pd.setMessage(连接到Loofre网络);
pd.setCancelable(false);
pd.show();



保护字符串doInBackground(String ... markerGetUrl){
try {
//构造OpenWeatherMap查询的URL
//可能的参数可以在OWM的预测API页面获得,位于
// http://openweathermap.org/API#forecast
URL url1 =新的URL(url);

//创建OpenWeatherMap的请求,并打开连接
urlConnection =(HttpURLConnection)url1.openConnection();
urlConnection.setRequestMethod(GET);
urlConnection.connect();

//将输入流读入字符串
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream == null){
//无事可做。
返回null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));

字符串行;
while((line = reader.readLine())!= null){
//因为是JSON,所以不需要添加换行符(它不会影响解析)
/ /但是,如果打印出完整的
//缓冲区以进行调试,它确实使调试变得更加容易。
buffer.append(line +\\\
);
}

if(buffer.length()== 0){
// Stream是空的。解析没有意义。
返回null;
}
forecastJsonStr = buffer.toString();
} catch(IOException e){
Log.e(PlaceholderFragment,Error,e);
//如果代码没有成功获取天气数据,则尝试
//来解析它没有意义。
forecastJsonStr =错误,引发异常。;
} finally {
if(urlConnection!= null){
urlConnection.disconnect();

if(reader!= null){
try {
reader.close();
catch(final IOException e){
Log.e(PlaceholderFragment,Error closing stream,e);
}
}
}
返回forecastJsonStr;

}

//执行后
$ b $保护无效onPostExecute(字符串标记){


Log.d(字符串响应,标记);

Toast.makeText(MainActivity.this,绘制Thekha,Toast.LENGTH_LONG).show();

尝试{
JSONArray jsonArray = new JSONArray(markers);
for(int i = 0; i< jsonArray.length(); i ++){
//创建json数据中每个位置的标记
JSONObject jsonObject = jsonArray.getJSONObject(i );
String placeName = jsonObject.getString(name);
String placeAddress = jsonObject.getString(address);
double latitude = jsonObject.getJSONArray(latlang)。getDouble(0);
double longitude = jsonObject.getJSONArray(latlang)。getDouble(1);
LatLng loc =新LatLng(经度,纬度);
//标记大小更改代码
int height = 150;
int width = 150;
BitmapDrawable bitmapDrawable =(BitmapDrawable)getResources()。getDrawable(R.drawable.thekhaicon);
位图b = bitmapDrawable.getBitmap();
位图smallMarker = Bitmap.createScaledBitmap(b,width,height,false);
mMap.clear();

mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
.title(placeName)
.snippet(placeAddress)
.position(loc));

mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
.title(placeName)
.snippet(placeAddress)
.position(new LatLng(gps.getLatitude(),gps.getLongitude())));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(),gps.getLongitude()),12);
map.animateCamera(cameraUpdate);
}
pd.dismiss();
} catch(JSONException e){
e.printStackTrace();
}

}
}







@Override
public void onBackPressed(){
DrawerLayout drawer =(DrawerLayout)findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();



@Override
public boolean onCreateOptionsMenu(菜单菜单){
//使菜单膨胀;这会将项目添加到操作栏(如果存在)。
getMenuInflater()。inflate(R.menu.main,menu);
返回true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
// Handle action bar item clicks here here。操作栏将
//自动处理Home / Up按钮上的点击,只要您在AndroidManifest.xml中指定了一个父活动,就可以长按
//。
int id = item.getItemId();

// noinspection SimplifiableIfStatement
if(id == R.id.action_settings){
return true;
}

返回super.onOptionsItemSelected(item);

$ b @SuppressWarnings(StatementWithEmptyBody)
@Override
public boolean onNavigationItemSelected(MenuItem item){
// Handle navigation view item clicks here 。
int id = item.getItemId();

if(id == R.id.nav_camera){
//处理相机动作
}否则if(id == R.id.nav_gallery){

} else if(id == R.id.nav_slideshow){

} else if(id == R.id.nav_manage){

}其他if(id == R.id.call_us){
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(tel:+919717001947));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在此请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String [] permissions,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
返回true;
}
startActivity(intent);

} else if(id == R.id.about_us){
Intent intent = new Intent(this,ScrollingActivity.class);
this.startActivity(intent);

}

DrawerLayout drawer =(DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
返回true;

$ b @Override
public void onMapReady(GoogleMap googleMap){
Toast.makeText(this,Connecting Server,Toast.LENGTH_LONG).show() ;
mMap = googleMap;
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){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在这里请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String []权限,
// int [] grantResults)
//处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
}
//工具栏和其他与map相关的工具uiSettings
// mMap.setMyLocationEnabled(true);
mMap.getUiSettings()。setZoomControlsEnabled(true);
mMap.getUiSettings()。setMapToolbarEnabled(true);
mMap.getUiSettings()。setMyLocationButtonEnabled(true);
double lat = 0;
double lon = 0;
GPSTracker gps =新GPSTracker(MainActivity.this);

if(gps.canGetLocation())
{
lat = gps.getLatitude();
lon = gps.getLongitude();
}

尝试{
LatLng myloc = new LatLng(lat,lon);
mMap.addMarker(new MarkerOptions()。position(myloc).title(Marker in my Locaiton));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myloc));
RetriveMarkerTask markerTask = new RetriveMarkerTask(MainActivity.this);
markerTask.execute(url);
} catch(Exception e){
Toast.makeText(this,Can not fetch data,Toast.LENGTH_LONG).show();
}


}

这里是GPSTracker .java类。

  import android.app.AlertDialog; 
导入android.app.Service;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.location.Location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.os.IBinder;
导入android.provider.Settings;
导入android.util.Log;

公共类GPSTracker延伸Service实现LocationListener {

private final Context mContext;

// GPS状态标志
boolean isGPSEnabled = false;

//网络状态标志
boolean isNetworkEnabled = false;

// GPS状态标志
boolean canGetLocation = false;

位置位置; //位置
双纬度; //纬度
双经度; // longitude

//改变的最小距离以米为单位的更新
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10米

//以毫秒为单位的最小更新时间间隔
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟

//声明位置管理器
受保护的LocationManager locationManager;

公共GPSTracker(上下文环境){
this.mContext = context;
getLocation();


public Location getLocation(){
try {
locationManager =(LocationManager)mContext
.getSystemService(LOCATION_SERVICE);

//获取GPS状态
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

//获取网络状态
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(!isGPSEnabled&&!isNetworkEnabled){
//没有启用网络提供程序
} else {
this.canGetLocation = true;
//首先从网络提供商获取位置
if(isNetworkEnabled){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this );
Log.d(网络,网络);
if(locationManager!= null){
// location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();


$ b //如果GPS启用使用GPS服务获得经纬度
if(isGPSEnabled){
if(location == null ){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(已启用GPS,已启用GPS);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();





} catch(Exception e){
e.printStackTrace();
}

返回地点;

$ b $ **
*停止使用GPS监听器
*调用此函数将停止在您的应用中使用GPS
* * /
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}

//返回纬度
返回纬度;
}

/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}

//返回经度
返回经度;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

//设置对话框标题
alertDialog.setTitle(GPS is settings);

// Setting Dialog Message
alertDialog.setMessage(\"GPS is not enabled. Do you want to go to settings menu?\");

// On pressing Settings button
alertDialog.setPositiveButton(\"Settings\", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button
alertDialog.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

//显示提示信息
alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}

}


I am developing an app where I am using AsyncTask to plot a marker. I am trying to plot marker on onPostExeution() for current location and move my camera to current location.I have tried few ways to acheive this but unfortunately app crashes.So guys can you guide me to plot a marker on current location and move my camera to that place once i receive location update in onPostExecute().

Here's my code -

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {

SupportMapFragment sMapFragment;
public GoogleMap mMap;
private HttpURLConnection urlConnection = null;
private BufferedReader reader = null;
private String forecastJsonStr = null;
private String url = "my_url";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    sMapFragment = SupportMapFragment.newInstance();


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    sMapFragment.getMapAsync(this);
    android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
    sFM.beginTransaction().add(R.id.Map, sMapFragment).commit();

}

//Search option

public void onMapSearch(View view) throws IOException {

    //hide button when button is pressed
    InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

    //preview the entered address as an Tost in bar
    EditText locationSearch = (EditText) findViewById(R.id.editText);
    String location = locationSearch.getText().toString();

    //this will animate camera and zoom 12.0f
    mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));


    //further address search codes
    List<Address> addressList = null;

    //if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
    if (locationSearch.getText().toString().equals("")) {
        Toast.makeText(this, "Please enter an Address", Toast.LENGTH_LONG).show();
    } else {

        //process of exception handling and finding location
        if (location != null || !location.equals("")) {
            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //if address is greater than one then these processes will happen

            if (addressList.size() > 0) {
                Address address = addressList.get(0);
                LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                mMap.addMarker(new MarkerOptions()
                        .position(latLng)
                        .title(location + " is Here ")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
                mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                Toast.makeText(this, location + " is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
                        .show(); //popup type to show entered data
            } else {
                //process where entered entry will not gonna find , this will gonna a toast to show popup

                Toast.makeText(this, "Entered Address Not Found", Toast.LENGTH_LONG).show();

            }
        }

    }
}

//Async task

ProgressDialog pd = null;

private class RetriveMarkerTask extends AsyncTask<String, Void, String> {
    private Context context;


    public RetriveMarkerTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        pd = new ProgressDialog(MainActivity.this);
        pd.setTitle("Please wait ...");
        pd.setMessage("Connecting to Loofre Network");
        pd.setCancelable(false);
        pd.show();

    }

    protected String doInBackground(String... markerGetUrl) {
        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are avaiable at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            URL url1 = new URL(url);

            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url1.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            forecastJsonStr = "Error, an exception was raised.";
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }
        return forecastJsonStr;

    }

    //on post execution

    protected void onPostExecute(String markers) {


        Log.d("string response", markers);

        Toast.makeText(MainActivity.this, "Plotting Thekha", Toast.LENGTH_LONG).show();

        try {
            JSONArray jsonArray = new JSONArray(markers);
            for (int i = 0; i < jsonArray.length(); i++) {
                //create marker of each place in the json data
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String placeName = jsonObject.getString("name");
                String placeAddress = jsonObject.getString("address");
                double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
                double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
                LatLng loc = new LatLng(latitude, longitude);
                //marker size change code
                int height = 150;
                int width = 150;
                BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.thekhaicon);
                Bitmap b = bitmapDrawable.getBitmap();
                Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
                //marker size change code ends here
                //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));

                mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
                        .title(placeName)
                        .snippet(placeAddress)
                        .position(loc)

                );

                LatLng dwarka = new LatLng(28.570317, 77.32182);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dwarka, 13));
                mMap.addMarker(
                        new MarkerOptions()
                                .title("Wine Beer Liquor Shop, Sector 18, Noida")
                                .snippet("Sector 18, Near Centre Stage Mall, Noida")
                                .position(dwarka));
            }
            pd.dismiss();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}







@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.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);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.call_us) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:+919717001947"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != 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 true;
        }
        startActivity(intent);

    } else if (id == R.id.about_us) {
        Intent intent = new Intent(this,ScrollingActivity.class);
        this.startActivity(intent);

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    Toast.makeText(this, "Connecting Server", Toast.LENGTH_LONG).show();
    mMap = googleMap;

    try {
        RetriveMarkerTask markerTask = new RetriveMarkerTask(MainActivity.this);
        markerTask.execute(url);
    }catch (Exception e){
        Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show();
    }
    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) {
        // 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.
    }
    //tool bar and other tool related on map uiSettings
    // mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setMapToolbarEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

}

my manifest.xml file -

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSWEVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:name="android.support.multidex.MultiDexApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="Thekha"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"></activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyAma5WZ9H5yskkt3AsQwc3aeQOFCyc9aGo" />

    <activity android:name=".LoginActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ScrollingActivity"
        android:label="@string/title_activity_scrolling"
        android:theme="@style/AppTheme.NoActionBar"></activity>
</application>

解决方案

Hey @Kuldeep try this out.

        public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {

    SupportMapFragment sMapFragment;
    public GoogleMap mMap;
    private HttpURLConnection urlConnection = null;
    private BufferedReader reader = null;
    private String forecastJsonStr = null;
    private String url = "my_url";

    @Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    sMapFragment = SupportMapFragment.newInstance();


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    sMapFragment.getMapAsync(this);
    android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
    sFM.beginTransaction().add(R.id.Map, sMapFragment).commit();

}

//Search option

public void onMapSearch(View view) throws IOException {

    //hide button when button is pressed
    InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

    //preview the entered address as an Tost in bar
    EditText locationSearch = (EditText) findViewById(R.id.editText);
    String location = locationSearch.getText().toString();

    //this will animate camera and zoom 12.0f
    mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));


    //further address search codes
    List<Address> addressList = null;

    //if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
    if (locationSearch.getText().toString().equals("")) {
        Toast.makeText(this, "Please enter an Address", Toast.LENGTH_LONG).show();
    } else {

        //process of exception handling and finding location
        if (location != null || !location.equals("")) {
            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //if address is greater than one then these processes will happen

            if (addressList.size() > 0) {
                Address address = addressList.get(0);
                LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                mMap.addMarker(new MarkerOptions()
                        .position(latLng)
                        .title(location + " is Here ")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
                mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                Toast.makeText(this, location + " is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
                        .show(); //popup type to show entered data
            } else {
                //process where entered entry will not gonna find , this will gonna a toast to show popup

                Toast.makeText(this, "Entered Address Not Found", Toast.LENGTH_LONG).show();

            }
        }

    }
}

//Async task

ProgressDialog pd = null;

private class RetriveMarkerTask extends AsyncTask<String, Void, String> {
    private Context context;


    public RetriveMarkerTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        pd = new ProgressDialog(MainActivity.this);
        pd.setTitle("Please wait ...");
        pd.setMessage("Connecting to Loofre Network");
        pd.setCancelable(false);
        pd.show();

    }

    protected String doInBackground(String... markerGetUrl) {
        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are avaiable at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            URL url1 = new URL(url);

            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url1.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            forecastJsonStr = "Error, an exception was raised.";
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }
        return forecastJsonStr;

    }

    //on post execution

    protected void onPostExecute(String markers) {


        Log.d("string response", markers);

        Toast.makeText(MainActivity.this, "Plotting Thekha", Toast.LENGTH_LONG).show();

        try {
            JSONArray jsonArray = new JSONArray(markers);
            for (int i = 0; i < jsonArray.length(); i++) {
                //create marker of each place in the json data
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String placeName = jsonObject.getString("name");
                String placeAddress = jsonObject.getString("address");
                double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
                double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
                LatLng loc = new LatLng(latitude, longitude);
                //marker size change code
                int height = 150;
                int width = 150;
                BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.thekhaicon);
                Bitmap b = bitmapDrawable.getBitmap();
                Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
                 mMap.clear();

                mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
                        .title(placeName)
                        .snippet(placeAddress)
                        .position(loc));

mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
                        .title(placeName)
                        .snippet(placeAddress)
                        .position(new LatLng(gps.getLatitude(),gps.getLongitude())));
     CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(),gps.getLongitude()), 12); 
     map.animateCamera(cameraUpdate);
               }
            pd.dismiss();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}







@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.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);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.call_us) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:+919717001947"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != 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 true;
        }
        startActivity(intent);

    } else if (id == R.id.about_us) {
        Intent intent = new Intent(this,ScrollingActivity.class);
        this.startActivity(intent);

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
 public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Connecting Server", Toast.LENGTH_LONG).show();
        mMap = googleMap;
    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) {
                // 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.
        }
        //tool bar and other tool related on map uiSettings
        // mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true); 
    double lat=0;
    double lon=0;
          GPSTracker gps=new GPSTracker(MainActivity.this);

         if(gps.canGetLocation())
          {
             lat=gps.getLatitude();
             lon=gps.getLongitude();
             }

         try {
              LatLng myloc= new LatLng(lat,lon);
        mMap.addMarker(new MarkerOptions().position(myloc).title("Marker in my Locaiton"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myloc));
            RetriveMarkerTask markerTask = new RetriveMarkerTask(MainActivity.this);
            markerTask.execute(url);
        }catch (Exception e){
            Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show();
        }


    }

Here is GPSTracker.java class.

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                      //  location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

这篇关于在async-task onPostExecution之后在当前位置绘制一个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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