谷歌地图查找当前位置和附近的地方
Posted
技术标签:
【中文标题】谷歌地图查找当前位置和附近的地方【英文标题】:Google map to find current location and nearby places 【发布时间】:2017-06-07 13:51:50 【问题描述】:我想在我的 android 应用中添加一个谷歌地图插件来获取用户的当前位置并显示附近的医院。 如何获取当前位置和附近的地方?有人可以给我一个方向吗?
【问题讨论】:
请参考此链接:androidtutorialpoint.com/intermediate/… 语法修正、拼写和标签添加。 除了@Akash 链接之外,也试试这个链接:wptrafficanalyzer.in/blog/… 【参考方案1】:按照以下步骤进行
this tutorial 熟悉 Android 谷歌地图和这个 API 2。
查看 this answer 或此 another answer 和 API 2 以获取当前位置
使用 Google Place API 获取您所在位置附近的地点,要使用 Place Api,请参阅 this blog。
使用 this blog with source code 在地图上显示标记,并使用 API 2 进行气球叠加。
在地图上的两点之间绘制路线 查看这些链接Link1和Link2以及这个Great Answer。
【讨论】:
【参考方案2】:请按照以下代码您将获得附近正在工作的医院。:)
您可以根据自己的意愿更改此类型,例如医院、咖啡厅、餐厅.... 看看它是如何运作的:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener
private GoogleMap mMap;
LocationManager locationManager;
CoordinatorLayout mainCoordinatorLayout;
String type;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable())
return;
setContentView(R.layout.activity_maps);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
type="hospital";
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mainCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.mainCoordinatorLayout);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
showLocationSettings();
private void showLocationSettings()
Snackbar snackbar = Snackbar
.make(mainCoordinatorLayout, "Location Error: GPS Disabled!",
Snackbar.LENGTH_LONG)
.setAction("Enable", new View.OnClickListener()
@Override public void onClick(View v)
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
);
snackbar.setActionTextColor(Color.RED);
snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView
.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
@Override
public void onMapReady(GoogleMap googleMap)
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)
return;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
showCurrentLocation();
private void showCurrentLocation()
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
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;
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null)
onLocationChanged(location);
locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
private void loadNearByPlaces(double latitude, double longitude)
StringBuilder googlePlacesUrl =
new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=").append(type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);
JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
new Response.Listener<JSONObject>()
@Override
public void onResponse(JSONObject result)
Log.i(TAG, "onResponse: Result= " + result.toString());
parseLocationResult(result);
,
new Response.ErrorListener()
@Override public void onErrorResponse(VolleyError error)
Log.e(TAG, "onErrorResponse: Error= " + error);
Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
);
AppController.getInstance().addToRequestQueue(request);
private void parseLocationResult(JSONObject result)
String id, place_id, placeName = null, reference, icon, vicinity = null;
double latitude, longitude;
try
JSONArray jsonArray = result.getJSONArray("results");
if (result.getString(STATUS).equalsIgnoreCase(OK))
mMap.clear();
for (int i = 0; i < jsonArray.length(); i++)
JSONObject place = jsonArray.getJSONObject(i);
id = place.getString(SUPERMARKET_ID);
place_id = place.getString(PLACE_ID);
if (!place.isNull(NAME))
placeName = place.getString(NAME);
if (!place.isNull(VICINITY))
vicinity = place.getString(VICINITY);
latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LATITUDE);
longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LONGITUDE);
reference = place.getString(REFERENCE);
icon = place.getString(ICON);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(latitude, longitude);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
Toast.makeText(getBaseContext(), jsonArray.length() + " Supermarkets found!",
Toast.LENGTH_LONG).show();
else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS))
Toast.makeText(getBaseContext(), "No Supermarket found in 5KM radius!!!",
Toast.LENGTH_LONG).show();
catch (JSONException e)
e.printStackTrace();
Log.e(TAG, "parseLocationResult: Error=" + e.getMessage());
@Override
public void onLocationChanged(Location location)
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
loadNearByPlaces(latitude, longitude);
@Override
public void onStatusChanged(String s, int i, Bundle bundle)
@Override
public void onProviderEnabled(String s)
@Override
public void onProviderDisabled(String s)
private boolean isGooglePlayServicesAvailable()
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
if (apiAvailability.isUserResolvableError(resultCode))
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
else
Log.i(TAG, "This device is not supported.");
finish();
return false;
return true;
这是xml文件。
<FrameLayout
android:layout_
android:layout_
xmlns:android="http://schemas.android.com/apk/res/android">
<fragment android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
它在我身边工作。请添加 api 密钥并享受它。希望这个帮助:)
【讨论】:
以上是关于谷歌地图查找当前位置和附近的地方的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Android 谷歌地图中显示附近的地方,如自动取款机、医院?