Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android mMap.setMyLocationEnabled(真);不在片段映射中工作_Android_Google Maps_Permissions_Location - Fatal编程技术网

Android mMap.setMyLocationEnabled(真);不在片段映射中工作

Android mMap.setMyLocationEnabled(真);不在片段映射中工作,android,google-maps,permissions,location,Android,Google Maps,Permissions,Location,我已经从menifest和runtime获得了所有必需的权限,但它在我的设备中不适用于google地图中的当前位置 public class MapFragment extends Fragment implements OnMapReadyCallback, AdapterView.OnItemClickListener { View view; ImageView locAddress; AppLocationService appLocationService; AutoCompleteT

我已经从menifest和runtime获得了所有必需的权限,但它在我的设备中不适用于google地图中的当前位置

public class MapFragment extends Fragment implements OnMapReadyCallback, AdapterView.OnItemClickListener {
View view;
ImageView locAddress;
AppLocationService appLocationService;
AutoCompleteTextView edtStartPoint;
EditText togo;
private static final String LOG_TAG = "Google Places Autocomplete";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "MY_API_KEY";
private static final int REQUEST_FINE_LOCATION = 11;
private GoogleMap mMap;

ImageView imgLoc;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.activity_main, container, false);
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);

    if (mapFragment != null) {
        mapFragment.getMapAsync(this);
    }
    locAddress = view.findViewById(R.id.locAddress);
    edtStartPoint = view.findViewById(R.id.edtStartPoint);
    imgLoc = view.findViewById(R.id.imgLoc);
    edtStartPoint.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item_text));
    edtStartPoint.setOnItemClickListener(this);
    appLocationService = new AppLocationService(
            getActivity());
    if (InternetConnection.checkConnection(getActivity())) {

    } else {
        showSnack(true);
    }
    return view;
}

@Override
public void onMapReady(GoogleMap map) {

    mMap = map;
    LatLng sydney = new LatLng(-34, 151);
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mMap.setTrafficEnabled(false);
    mMap.setIndoorEnabled(false);
    mMap.setBuildingsEnabled(false);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    if (checkPermissions()) {
        setMyLocationEnabled();
    }
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

    map.setOnMapClickListener(latLng -> {
        BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
        bottomSheetFragment.show(getActivity().getSupportFragmentManager(), bottomSheetFragment.getTag());
    });


}

public static ArrayList autocomplete(String input) {
    ArrayList resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        sb.append("&components=country:gr");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));
        Log.e("@@sb", sb.toString());

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e("@@", "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        Log.e("@@", "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {

        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");


        resultList = new ArrayList(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
            System.out.println("====");
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        Log.e("@@", "Cannot process JSON results", e);
    }

    return resultList;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    String str = (String) parent.getItemAtPosition(position);
    Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}

class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
    private ArrayList resultList;

    public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return String.valueOf(resultList.get(index));
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }
}


private void showSnack(boolean isConnected) {
    final CoordinatorLayout coordinatorLayout = view.findViewById(R.id.coordinatorLayout);
    Snackbar snackbar = Snackbar
            .make(coordinatorLayout, "No Internet", Snackbar.LENGTH_LONG)
            .setAction("OK", view -> {
                Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "ok", Snackbar.LENGTH_SHORT);
                snackbar1.show();
            });
    snackbar.show();
}

private boolean checkPermissions() {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        requestPermissions();
        return false;
    }
}

private void requestPermissions() {
    ActivityCompat.requestPermissions(getActivity(),
            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
            REQUEST_FINE_LOCATION);
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_FINE_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setMyLocationEnabled();
            } else {
            }
        }
    }
}

private void setMyLocationEnabled() {
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            //TODO:
        }
    });
}
}
公共类MapFragment扩展了MapReadyCallback、AdapterView.OnItemClickListener上的片段实现{
视图;
图像视图地址;
AppLocationService AppLocationService;
自动完成文本视图edtStartPoint;
多哥;
私有静态最终字符串日志\u TAG=“Google Places Autocomplete”;
私有静态最终字符串PLACES\u API\u BASE=”https://maps.googleapis.com/maps/api/place";
私有静态最终字符串类型\u AUTOCOMPLETE=“/AUTOCOMPLETE”;
私有静态最终字符串输出_JSON=“/JSON”;
私有静态最终字符串API\u KEY=“MY\u API\u KEY”;
私有静态最终整型请求\精细\位置=11;
私有谷歌地图;
ImageView imgLoc;
@可空
@凌驾
创建视图时的公共视图(LayoutFlater充气机、@Nullable ViewGroup容器、@Nullable Bundle savedInstanceState){
视图=充气机。充气(R.layout.activity\u main,容器,假);
SupportMapFragment mapFragment=(SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.mapView);
if(mapFragment!=null){
getMapAsync(这个);
}
locAddress=view.findviewbyd(R.id.locAddress);
edtStartPoint=view.findViewById(R.id.edtStartPoint);
imgLoc=view.findviewbyd(R.id.imgLoc);
setAdapter(新的GooglePlacesAutocompleteAdapter(getActivity(),R.layout.list_item_text));
edtStartPoint.setOnItemClickListener(此);
appLocationService=新的appLocationService(
getActivity());
if(InternetConnection.checkConnection(getActivity())){
}否则{
show零食(真);
}
返回视图;
}
@凌驾
已于4月1日公开作废(谷歌地图){
mMap=map;
悉尼LatLng=新LatLng(-34151);
mMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
mMap.setTrafficEnabled(假);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.addMarker(新MarkerOptions().position(sydney.title)(“悉尼的标记”);
mMap.moveCamera(CameraUpdateFactory.newLatLng(悉尼));
if(checkPermissions()){
setMyLocationEnabled();
}
mMap.getUiSettings().setMyLocationButtonEnabled(true);
map.setOnMapClickListener(latLng->{
BottomSheetFragment BottomSheetFragment=新的BottomSheetFragment();
show(getActivity().getSupportFragmentManager(),bottomSheetFragment.getTag());
});
}
公共静态ArrayList自动完成(字符串输入){
ArrayList resultList=null;
HttpURLConnection conn=null;
StringBuilder jsonResults=新建StringBuilder();
试一试{
StringBuilder sb=新的StringBuilder(PLACES\u API\u BASE+TYPE\u AUTOCOMPLETE+OUT\u JSON);
sb.追加(“?key=“+API_key”);
sb.追加(“&components=国家:gr”);
sb.append(“&input=“+urlcoder.encode”(输入,“utf8”));
Log.e(“@@sb”,sb.toString());
URL=新URL(sb.toString());
conn=(HttpURLConnection)url.openConnection();
InputStreamReader in=新的InputStreamReader(conn.getInputStream());
//将结果加载到StringBuilder中
int-read;
char[]buff=新字符[1024];
while((read=in.read(buff))!=-1){
附加(buff,0,read);
}
}捕获(格式错误){
Log.e(“@@”,“错误处理位置API URL”,e);
返回结果列表;
}捕获(IOE异常){
Log.e(“@@”,“连接到位置API时出错”,e);
返回结果列表;
}最后{
如果(conn!=null){
连接断开();
}
}
试一试{
JSONObject jsonObj=新的JSONObject(jsonResults.toString());
JSONArray predsjssonarray=jsonObj.getJSONArray(“预测”);
resultList=新的ArrayList(predsjSonaray.length());
对于(int i=0;i0){
notifyDataSetChanged();
}否则{
不