【发布时间】:2020-02-02 00:59:21
【问题描述】:
我是一个非常新手的程序员。 我正在使用处理程序将我的位置数据从服务获取到我的主要活动,但我想使用服务中的代码更新地图。
GPS 坐标是通过处理程序正确发送的,但我似乎对如何使用处理程序通过更新地图上的地图/图标来实际呈现数据感到困惑。
地图始终将标记置于 0.0,也不会将地图定位在通过处理程序发送的新位置。
//get GPS latitude and Longitude from service here
private void displayLatLong() {
final TextView latitudeView = (TextView) findViewById(R.id.latitude);
final TextView longitudeView = (TextView) findViewById(R.id.longitude);
final TextView latitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final TextView longitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
double latitude = 0.0;
double longitude = 0.0;
//latitudeCoords = "not empty"; //debug
//longitudeCoords = "not empty"; //debug
if(bound && locationService != null) {
latitude = locationService.getLastLatitude();
longitude = locationService.getlastLongitude();
}
String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude);
String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude);
latitudeView.setText(latitudeStr);
longitudeView.setText(longitutdeStr);
latCoords = latitude;
longCoords = longitude;
// longitudeCoordsView.setText(longitudeCoords); //debug
// latitudeCoordsView.setText(longitudeCoords); //debug
handler.postDelayed(this, 1000);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Bind location service here so it keeps running even if activity is stopped.
Intent intent = new Intent(this, LocationService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
displayDistance();
displayLatLong();
}
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
LatLng player= new LatLng(latCoords, longCoords);
mMap.addMarker(new MarkerOptions().position(player).title("current player position"));//set marker with player position and description
mMap.moveCamera(CameraUpdateFactory.newLatLng(player)); //move Camera to player position
}locat
【问题讨论】:
-
您没有分配
locationService引用,因此它始终为空。不过,总的来说,您在这里采用的方法并不好。您不应该直接引用服务。此外,您正在尝试轮询值,而您应该等待服务一旦获得位置的回调。您可以使用绑定服务,或使用广播接收器,请参见此处:stackoverflow.com/questions/10179470/… -
但我正在从服务获取位置数据,因为我有这个 ` String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude); String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude); latitudeView.setText(latitudeStr); longitudeView.setText(longitutdeStr); ` 准确显示当前 GPS 坐标,为什么我不能在地图上使用这些坐标?我已经在这段代码中使用了绑定服务。我只是没有发布完整的代码。
标签: android google-maps location handler