我制作了纬度和经度全局变量。
它在MyLocationListener
类中工作正常,因为它显示当前位置的纬度和经度,但是当它在webview中加载url(http://maps.google.com/maps?" + "saddr="
+ currentLattitude + "," + currentLongtitude
+ "&daddr=27.11,85.11")
)时,它会加载值0和0。
为什么?
public class ShowMapActivity extends Activity {
private WebView webView;
double currentLattitude;
double currentLongtitude;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://maps.google.com/maps?" + "saddr="
+ currentLattitude + "," + currentLongtitude
+ "&daddr=27.11,85.11");
}
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
currentLattitude = loc.getLatitude();
currentLongtitude = loc.getLongitude();
Toast.makeText(
getApplicationContext(),
"Latitude is: " + currentLattitude + " Longitude is: "
+ currentLongtitude,
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText(getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
答案 0 :(得分:3)
尝试将这段代码放在onLocationChanged
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://maps.google.com/maps?" + "saddr="
+ currentLattitude + "," + currentLongtitude
+ "&daddr=27.11,85.11");
答案 1 :(得分:1)
在onLocationChanged(...)
webView.loadUrl("http://maps.google.com/maps?" + "saddr="
+ currentLattitude + "," + currentLongtitude
+ "&daddr=27.11,85.11");
答案 2 :(得分:1)
你的双变量给出了下面一行的默认值。因为在更新下面的位置之前正在执行
webView.loadUrl("http://maps.google.com/maps?" + "saddr="
+ currentLattitude + "," + currentLongtitude
+ "&daddr=27.11,85.11");
答案 3 :(得分:1)
因为您在onCreate()
函数中打开了WebView,并且您在onLocationChanged()
函数中获得了位置。为了解决这个问题,如果你想要总是在更改位置时更新Web视图,只需将它放在函数onLocationChanged()
中,如果你想在它可以使用布尔变量时加载它onLocationChanged()
表示这是您第一次使用此功能。
提高效率:您最好在获得位置后删除更新以避免电池耗尽。