GoogleMaps显示“本地人”在错误的位置上 [英] GoogleMaps displaying "locals" on wrong position

查看:79
本文介绍了GoogleMaps显示“本地人”在错误的位置上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示手机的 CurrentPosition ,并在该位置附近显示所有 bar | cafe



CurrentPosition 起作用。

但是酒吧/咖啡馆的显示是错误的。看起来他们是从维也纳中心出现的,而不是从我的手机的位置出现。



如果有人能够找到问题,我们将非常感激。



MapsActivity.java

  package androfenix.currentpositionandplacesnearby; 

导入android.Manifest;
导入android.content.pm.PackageManager;
导入android.location.Location;
导入android.os.AsyncTask;
导入android.os.Build;
导入android.support.v4.app.ActivityCompat;
导入android.os.Bundle;
导入android.support.v4.content.ContextCompat;
导入android.support.v7.app.AppCompatActivity;
导入android.util.Log;
导入android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
导入com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
导入com.google.android.gms.maps.model.Marker;
导入com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
导入java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


公共类MapsActivity扩展了AppCompatActivity实现的OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {

私人GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
位置mLastLocation;
标记mCurrLocationMarker;
LocationRequest mLocationRequest;

LatLng latLng;
double mLatitude = 0;
double mLongitude = 0;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

if(android.os.Build.VERSION.SDK_INT> = Build.VERSION_CODES.M){
checkLocationPermission();
}
//获取SupportMapFragment并在地图准备好使用时得到通知。
SupportMapFragment mapFragment =(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;

// Mit setMapType setzen wir das Aussehen der Karte aufHybrid
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

//初始化Google Play服务
if(android.os.Build.VERSION.SDK_INT> = Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(this ,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
buildGoogleApiClient();

mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);



$ b protected synchronized buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this )
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

mGoogleApiClient.connect();
}

@Override
public void onPause()
{
super.onPause();
//取消注册位置回调:
if(mGoogleApiClient!= null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);

}

@Override
public void onConnected(Bundle bundle){

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);



@Override
public void onConnectionSuspended(int i){
}

@Override
public void onLocationChanged(Location location){

mLastLocation = location;
if(mCurrLocationMarker!= null){
mCurrLocationMarker.remove();
}

//为当前位置创建一个LatLng对象
latLng = new LatLng(location.getLatitude(),location.getLongitude());

mLatitude = location.getLatitude();
mLongitude = location.getLongitude();

//放置当前位置标记
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(当前位置);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);

//移动地图相机
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

//停止位置更新
if(mGoogleApiClient!= null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}

StringBuilder sbValue = new StringBuilder(sbMethod());
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());

$ b @Override
public void onConnectionFailed(ConnectionResult connectionResult){
}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){

if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){

//询问用户是否需要解释
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)){

//显示解释给用户*异步* - 不要阻止
//此线程正在等待用户的响应!在用户
//看到解释后,再次尝试请求权限。

//一旦显示解释提示用户
ActivityCompat.requestPermissions(this,
new String [] {Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION) ;


}其他{
//无需解释,我们可以申请许可。
ActivityCompat.requestPermissions(this,
new String [] {Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
返回false;
} else {
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions [],int [] grantResults){
switch(requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION:{
//如果请求被取消,结果数组为空。
if(grantResults.length> 0
&&& amp; grantResults [0] == PackageManager.PERMISSION_GRANTED){

//授予权限。做你需要做的
//联系人相关的任务。
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){

if(mGoogleApiClient == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}

}其他{

// Permission denied,禁用取决于此权限的功能。
Toast.makeText(this,permission denied,Toast.LENGTH_LONG).show();
}
return;
}

//其他'case'行来检​​查此应用可能请求的其他权限。
//您可以根据您的要求在此添加其他案例陈述。



public StringBuilder sbMethod()throws SecurityException
{
StringBuilder sb = new StringBuilder(https://maps.googleapis.com /地图/ API /地点/ nearbysearch / JSON)?;
sb.append(location =+ mLatitude +,+ mLongitude);
sb.append(& radius = 50000);
sb.append(& sensor = true);
sb.append(& keyword =+bar | cafe);
sb.append(& key = SERVER API KEY);

Log.d(Map,url:+ sb.toString());

return sb;
}

私人类PlacesTask扩展AsyncTask< String,Integer,String>
{

String data = null;

//由此对象的execute()方法调用
@Override
保护字符串doInBackground(String ... url){
try {
data = downloadUrl(url [0]);
} catch(Exception e){
Log.d(Background Task,e.toString());
}
返回数据;
}

//完成doInBackground()方法执行后执行
@Override
保护void onPostExecute(String result){
ParserTask parserTask =新的ParserTask();

//开始以JSON格式解析Google地点
//调用ParserTask类的doInBackground()方法
parserTask.execute(result);



private String downloadUrl(String strUrl)throws IOException
{
String data =;
InputStream iStream = null;
HttpURLConnection urlConnection = null;
尝试{
URL url = new URL(strUrl);

//创建一个http连接与url进行通信
urlConnection =(HttpURLConnection)url.openConnection();

//连接到url
urlConnection.connect();

//从url读取数据
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line =; ((line = br.readLine())!= null){
sb.append(line);
while
}

data = sb.toString();

br.close();

} catch(Exception e){
Log.d(Exception,e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
返回数据;
}

private class ParserTask extends AsyncTask< String,Integer,List< HashMap< String,String>>> {

JSONObject jObject;

//由此对象的execute()方法调用
@Override
protected List< HashMap< String,String>> doInBackground(String ... jsonData){

List< HashMap< String,String>> places = null;
Place_JSON placeJson = new Place_JSON();

尝试{
jObject = new JSONObject(jsonData [0]);

places = placeJson.parse(jObject);

} catch(Exception e){
Log.d(Exception,e.toString());
}
返回地点;
}

//完成doInBackground()方法执行后执行
@Override
保护void onPostExecute(List< HashMap< String,String>> list ){

Log.d(Map,list size:+ list.size());
//清除所有现有的标记;
//mGoogleMap.clear();

(int i = 0; i< list.size(); i ++){

//创建一个标记
MarkerOptions markerOptions = new MarkerOptions( );

//从地点列表中获取地点
HashMap< String,String> hmPlace = list.get(i);


//获取地点的纬度
double lat = Double.parseDouble(hmPlace.get(lat));

//获取地点的经度
double lng = Double.parseDouble(hmPlace.get(lng));

//获取名称
字符串名称= hmPlace.get(place_name);

Log.d(Map,place:+ name);

//附近
字符串附近= hmPlace.get(nearby);

latLng =新LatLng(lat,lng);

//设置标记的位置
markerOptions.position(latLng);

markerOptions.title(name +:+ vicinity);

markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));

//在触摸的位置放置一个标记
标记m = mMap.addMarker(markerOptions);

// ZZZZZZZZZZZZZZZZZZZ
}
}
}
公共类Place_JSON {
$ b $ / **
*接收JSONObject并返回一个列表
* /
public List< HashMap< String,String>>解析(JSONObject jObject){

JSONArray jPlaces = null;
try {
/ **检索'places'数组中的所有元素* /
jPlaces = jObject.getJSONArray(results);
} catch(JSONException e){
e.printStackTrace();
}
/ **使用json对象数组调用getPlaces
*其中每个json对象表示一个位置
* /
return getPlaces(jPlaces);
}

private List< HashMap< String,String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List< HashMap< String,String>> placesList = new ArrayList< HashMap< String,String>>();
HashMap< String,String> place = null;

**取每个地方,解析并添加到列表对象* /
(int i = 0; i< placesCount; i ++){
try {
/ **调用getPlace与地方JSON对象来解析地点* /
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch(JSONException e){
e.printStackTrace();
}
}
返回placesList;
}

/ **
*解析Place JSON对象
* /
private HashMap< String,String> getPlace(JSONObject jPlace)
{

HashMap< String,String> place = new HashMap< String,String>();
String placeName =-NA-;
String vicinity =-NA-;
String latitude =;
String longitude =;
String reference =;

尝试{
//提取地名(如果有)
if(!jPlace.isNull(name)){
placeName = jPlace.getString(名称);
}

//提取地点附近区域(如果有)
if(!jPlace.isNull(vicinity)){
vicinity = jPlace.getString( );
}

latitude = jPlace.getJSONObject(geometry)。getJSONObject(location)。getString(lat);
longitude = jPlace.getJSONObject(geometry)。getJSONObject(location)。getString(lng);
reference = jPlace.getString(reference);

place.put(place_name,placeName);
place.put(邻近,附近);
place.put(lat,latitude);
place.put(lng,longitude);
place.put(reference,reference);

} catch(JSONException e){
e.printStackTrace();
}
返回地点;




解决方案

使用 Google地图API for Android ,您可以发现地点该设备当前位于。即设备当前报告的位置。如果您的应用使用了 / reference / com / google / android / gms / location / places / PlaceDetectionApirel =nofollow> PlaceDetectionApi.getCurrentPlace() 必须要求 ACCESS_FINE_LOCATION 权限。

以下代码示例检索设备最可能位于的地点列表,并记录每个地点的名称和可能性。

  PendingResult< PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi 
.getCurrentPlace(mGoogleApiClient,null);
result.setResultCallback(新的ResultCallback< PlaceLikelihoodBuffer>(){
@Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces){
for(PlaceLikelihood placeLikelihood:likelyPlaces){
Log.i(TAG,String.format(Place'%s'has likelihood:%g,
placeLikelihood.getPlace()。getName(),
placeLikelihood.getLikelihood()));
}
likelyPlaces.release();
}
});

PlacePicker 提供了一个UI对话框,显示交互式地图和附近地点的列表,包括与地理地址和当地企业相对应的地点。用户可以选择一个地方,然后您的应用程序可以检索所选地点的详细信息。



以下代码片段检索用户选择的地点:

  protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == PLACE_PICKER_REQUEST){
if(resultCode == RESULT_OK){
Place place = PlacePicker.getPlace(data,this);
String toastMsg = String.format(Place:%s,place.getName());
Toast.makeText(this,toastMsg,Toast.LENGTH_LONG).show();
}
}
}


i want to display the CurrentPosition of the mobile phone and display all bar|cafe nearby the position.

The CurrentPosition works.

But the displaying of the bars/cafes is wrong. It seems like they are showing up from the center of vienna and not from the position of my phone.

Would be really thankful if someone could find the problem

MapsActivity.java

package androfenix.currentpositionandplacesnearby;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

    LatLng latLng;
    double mLatitude=0;
    double mLongitude=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        //Mit setMapType setzen wir das Aussehen der Karte auf "Hybrid"
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();

                mMap.setMyLocationEnabled(true);
            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        mGoogleApiClient.connect();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        //Unregister for location callbacks:
        if (mGoogleApiClient != null)
        {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        // Create a LatLng object for the current location
        latLng = new LatLng(location.getLatitude(), location.getLongitude());

        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

        StringBuilder sbValue = new StringBuilder(sbMethod());
        PlacesTask placesTask = new PlacesTask();
        placesTask.execute(sbValue.toString());
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission(){

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted. Do the
                    // contacts-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }

    public StringBuilder sbMethod() throws SecurityException
    {
        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location=" + mLatitude + "," + mLongitude);
        sb.append("&radius=50000");
        sb.append("&sensor=true");
        sb.append("&keyword=" + "bar|cafe");
        sb.append("&key= SERVER API KEY ");

        Log.d("Map", "url: " + sb.toString());

        return sb;
    }

    private class PlacesTask extends AsyncTask<String, Integer, String>
    {

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result) {
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParserTask
            parserTask.execute(result);
        }
    }

    private String downloadUrl(String strUrl) throws IOException
    {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;
            Place_JSON placeJson = new Place_JSON();

            try {
                jObject = new JSONObject(jsonData[0]);

                places = placeJson.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String, String>> list) {

            Log.d("Map", "list size: " + list.size());
            // Clears all the existing markers;
            //mGoogleMap.clear();

            for (int i = 0; i < list.size(); i++) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);


                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                Log.d("Map", "place: " + name);

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                markerOptions.title(name + " : " + vicinity);

                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));

                // Placing a marker on the touched position
                Marker m = mMap.addMarker(markerOptions);

                // ZZZZZZZZZZZZZZZZZZZ
            }
        }
    }
    public class Place_JSON {

        /**
         * Receives a JSONObject and returns a list
         */
        public List<HashMap<String, String>> parse(JSONObject jObject) {

            JSONArray jPlaces = null;
            try {
                /** Retrieves all the elements in the 'places' array */
                jPlaces = jObject.getJSONArray("results");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            /** Invoking getPlaces with the array of json object
             * where each json object represent a place
             */
            return getPlaces(jPlaces);
        }

        private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
            int placesCount = jPlaces.length();
            List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> place = null;

            /** Taking each place, parses and adds to list object */
            for (int i = 0; i < placesCount; i++) {
                try {
                    /** Call getPlace with place JSON object to parse the place */
                    place = getPlace((JSONObject) jPlaces.get(i));
                    placesList.add(place);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return placesList;
        }

        /**
         * Parsing the Place JSON object
         */
        private HashMap<String, String> getPlace(JSONObject jPlace)
        {

            HashMap<String, String> place = new HashMap<String, String>();
            String placeName = "-NA-";
            String vicinity = "-NA-";
            String latitude = "";
            String longitude = "";
            String reference = "";

            try {
                // Extracting Place name, if available
                if (!jPlace.isNull("name")) {
                    placeName = jPlace.getString("name");
                }

                // Extracting Place Vicinity, if available
                if (!jPlace.isNull("vicinity")) {
                    vicinity = jPlace.getString("vicinity");
                }

                latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
                longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
                reference = jPlace.getString("reference");

                place.put("place_name", placeName);
                place.put("vicinity", vicinity);
                place.put("lat", latitude);
                place.put("lng", longitude);
                place.put("reference", reference);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return place;
        }
    }
}

解决方案

Using the Google Places API for Android, you can discover the place where the device is currently located. That is, the place at the device's currently-reported location. Examples of places include local businesses, points of interest, and geographic locations.

If your app uses PlaceDetectionApi.getCurrentPlace() must request the ACCESS_FINE_LOCATION permission.

The following code sample retrieves the list of places where the device is most likely to be located, and logs the name and likelihood for each place.

PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
  @Override
  public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
    for (PlaceLikelihood placeLikelihood : likelyPlaces) {
      Log.i(TAG, String.format("Place '%s' has likelihood: %g",
      placeLikelihood.getPlace().getName(),
      placeLikelihood.getLikelihood()));
}
likelyPlaces.release();
}
});

The PlacePicker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.

The following code snippet retrieves the place that the user has selected:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == PLACE_PICKER_REQUEST) {
    if (resultCode == RESULT_OK) {
    Place place = PlacePicker.getPlace(data, this);
    String toastMsg = String.format("Place: %s", place.getName());
    Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}

这篇关于GoogleMaps显示“本地人”在错误的位置上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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