首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将当前位置添加到fragment.class

将当前位置添加到fragment.class
EN

Stack Overflow用户
提问于 2018-05-28 16:26:31
回答 3查看 2.3K关注 0票数 0

我有点困惑...在网上找不到任何东西。

我想在选项卡片段中显示google地图。它工作得很好。但是如何设置片段的当前经度和纬度呢?

下面是xml:

代码语言:javascript
运行
复制
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TabMap"
android:background="#DBDBDB">

<com.google.android.gms.maps.MapView
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="60dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_marginTop="10dp">

</com.google.android.gms.maps.MapView>

地图片段

代码语言:javascript
运行
复制
public class TabMap extends Fragment implements OnMapReadyCallback{

GoogleMap mGoogleMap ;
MapView mMapView;
View mView;

Location location = new Location();

public TabMap() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mView =  inflater.inflate(R.layout.fragment_tab_map, container, false);
    return mView;
}


@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mMapView = (MapView) mView.findViewById(R.id.map);
    if(mMapView != null) {
        mMapView.onCreate(null);
        mMapView.onResume();
        mMapView.getMapAsync(this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {

    MapsInitializer.initialize(getContext());

    mGoogleMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    googleMap.addMarker(new MarkerOptions().position(new LatLng(51.1657, 10.4515)).title("Germany"));

    CameraPosition de = CameraPosition.builder().target(new LatLng(51.1657, 10.4515)).zoom(6).bearing(0).build();

    googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(de));
}

}

location.class

代码语言:javascript
运行
复制
public class Location extends AppCompatActivity {

private static final int REQUEST_CODE = 1000;
TextView txtLocation;
Button btnLocation, btnStop;

AutoCompleteTextView gMap;

FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case REQUEST_CODE: {
            if (grantResults.length > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {

                }
            }
        }
    }
}

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

    Button button = (Button) findViewById(R.id.button3);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), MainActivity.class);
            startActivityForResult(intent, 0);
        }
    });

    txtLocation = (TextView) findViewById(R.id.txtLocation);
    btnLocation = (Button) findViewById(R.id.btnLocation);
    btnStop = (Button) findViewById(R.id.btnStop);

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
    {

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
    } else {
        buildLocationRequest();
        buildLocationCallBack();

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        btnLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(Location.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(Location.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Location.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
                    return;
                }
                fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());

                btnLocation.setEnabled(!btnLocation.isEnabled());
                btnStop.setEnabled(!btnStop.isEnabled());
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(Location.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(Location.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Location.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
                    return;
                }
                fusedLocationProviderClient.removeLocationUpdates(locationCallback);

                btnLocation.setEnabled(!btnLocation.isEnabled());
                btnStop.setEnabled(!btnStop.isEnabled());
            }
        });

    }
}

public void buildLocationCallBack() {
    locationCallback = new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for(android.location.Location location:locationResult.getLocations())
                txtLocation.setText(String.valueOf(location.getLatitude())
                        + "/" +
                        String.valueOf(location.getLongitude()));
        }
    };
}

private void buildLocationRequest() {
    locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(5000);
    locationRequest.setFastestInterval(3000);
    locationRequest.setSmallestDisplacement(10);

}

}

所以。我有一个导航栏,可以选择添加它打开的位置( location.class),点击“当前位置”按钮,它会在TextView中显示纬度和经度。

但是如何将这些信息传递给TabMap.class,googleMap.addMarker方法呢?

提前感谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-05-28 17:33:12

onMapReady方法中替换此代码

代码语言:javascript
运行
复制
@Override
public void onMapReady(GoogleMap googleMap) {

    MapsInitializer.initialize(getContext());

    mGoogleMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mGoogleMap.setMyLocationEnabled(true);
    mGoogleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            if(location!=null){
                mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Germany"));
                CameraPosition de = CameraPosition.builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(6).bearing(0).build();
                mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(de));
            }               
        }
    });
}
票数 1
EN

Stack Overflow用户

发布于 2018-05-28 17:14:16

将此代码放在OnMapReady方法中:(它在蓝点中显示您的位置。)

代码语言:javascript
运行
复制
    @Override
    public void onMapReady(GoogleMap googleMap) {
        if (mMap != null) {
            return;
        }

        mMap = googleMap;
        if (mMap == null) {
            return;
        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);

        mMap.setOnMyLocationChangeListener(new mMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            if(location!=null){
                mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Germany"));
                CameraPosition de = CameraPosition.builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(6).bearing(0).build();
                mMap.moveCamera(CameraUpdateFactory.newCameraPosition(de));
            }               
        }
    });
    }
票数 1
EN

Stack Overflow用户

发布于 2018-05-28 17:39:41

你的问题是你不能让你的活动和片段通信。实现这一点的一个简单方法是使用库EventBus:https://github.com/greenrobot/EventBus

请阅读文档。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50562068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档