【发布时间】:2014-11-14 17:19:51
【问题描述】:
我手里有我服务器中几个地方的纬度和经度值。这些纬度和经度值是从服务器发送的,并在 android 手机上成功接收。现在我需要获取我的 android 手机的当前位置并计算离我当前位置最近的位置并将其标记在谷歌地图上。我知道如何在谷歌地图上标记一个地方,但我不知道如何使用纬度和经度计算从我当前位置到其他位置的距离,并找到距离我所在位置最近的位置。另外我不知道如何使用编码从 android 设备获取我当前的位置。我听说可以通过两种方式找到该位置,例如 1)使用最后一个已知位置和 2)使用 onlocation changed。使用最后一个已知位置方法的当前位置不适合我的应用程序。因此,我需要使用 onlocation 更改当前的纬度和经度。如果它不可用,则从纬度和经度获取位置坐标。
这是我在应用程序中打开谷歌地图并使用纬度和经度标记地点的代码。
public class Map extends Activity {
private GoogleMap googleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
double latitude =9.887262 ;
double longitude = 76.731675;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps ");
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
@Override
protected void onResume() {
super.onResume();
initilizeMap();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是它的布局文件..
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
【问题讨论】:
标签: android google-maps google-maps-markers google-maps-android-api-2 latitude-longitude