- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试在选项卡式 Activity 的 fragment 内实现支持 map fragment 。
我尝试设置 map ,并在 map 上设置标记。我成功地设置了 map ,但没有设置标记。我试图找到答案,但我无法自己解决问题。我希望得到一些帮助。
map fragment 代码:
public class Map_frag extends SupportMapFragment implements OnMapReadyCallback, GoogleMap.OnMapClickListener {
private SharedPreferences sp;
private Context context;
private float myLat, myLng, locLat, locLnf;
public GoogleMap map;
private Marker marker;
// Empty constructor
public Map_frag() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.map_fragment, container,false);
context = getContext();
sp = PreferenceManager.getDefaultSharedPreferences(context);
return v;
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
getMapAsync(this);
}
}
@Override
public void onMapReady(GoogleMap map) {
this.map = map;
onLocChange();
}
public void onLocChange(){
if (map ==null) {
map.clear();
if (marker !=null){
marker.remove();
}
myLat = Float.parseFloat(sp.getString("lat", "0"));
myLng = Float.parseFloat(sp.getString("lng", "0"));
LatLng latLng = new LatLng(myLat, myLng);
marker = map.addMarker( new MarkerOptions().position(latLng).title("myLoc"));
map.animateCamera(CameraUpdateFactory.
newLatLngZoom(latLng,15));
}
return;
}
@Override
public void onMapClick(LatLng latLng) {
}
}
还有 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00d05b5b">
<fragment android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/fragment2"
android:layout_gravity="center_horizontal"
tools:layout="@layout/place_autocomplete_fragment"/>
</LinearLayout>
最佳答案
onLocChange
这是什么? onLocationChanged
是一个覆盖方法。您可以使用它。
注意:您已经创建了自己的 onLocChange
方法并在 onMapReady
上调用它,因此它只会在 First 时被调用 时间。然后 onLocChange
不会被调用。但是如果你使用了 onLocationChanged
覆盖方法,每次位置改变时它都会被调用!!
在那里面
如果 block 覆盖了所有代码并且仅在 map 为 null 时才起作用,则首先将您删除,当 map 为 null 时没有添加标记的意义,将其远离..或像下面那样使用它
if(map==null){
//map null
} else {
// add code for markers
}
如果你使用上面的 block ,这应该与其他部分一起使用
if (currLocationMarker != null) {
// you already have a marker so when location changes you remove it and add a new one thats why you need this
currLocationMarker.remove();
}
latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions(); // just added to clear thingsyou you can add this where instance creates only once
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(iconForVehicleMarker);
currLocationMarker = mGoogleMap.addMarker(markerOptions);
想要一个包含您需要了解的所有内容的完整示例 (additional)?看看这里如何使用onMapReady
onLocationChaged
和相关方法
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
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.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* An activity that displays a map showing places around the device's current location.
*/
public class MapsActivityCurrentPlaces extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = MapsActivityCurrentPlaces.class.getSimpleName();
private GoogleMap mMap;
private CameraPosition mCameraPosition;
// The entry point to Google Play services, used by the Places API and Fused Location Provider.
private GoogleApiClient mGoogleApiClient;
// A request object to store parameters for requests to the FusedLocationProviderApi.
private LocationRequest mLocationRequest;
// The desired interval for location updates. Inexact. Updates may be more or less frequent.
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
// The fastest rate for active location updates. Exact. Updates will never be more frequent
// than this value.
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located.
private Location mCurrentLocation;
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// Build the Play services client for use by the Fused Location Provider and the Places API.
buildGoogleApiClient();
mGoogleApiClient.connect();
}
/**
* Get the device location and nearby places when the activity is restored after a pause.
*/
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
getDeviceLocation();
}
updateMarkers();
}
/**
* Stop location updates when the activity is no longer in focus, to reduce battery consumption.
*/
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
/**
* Saves the state of the map when the activity is paused.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mCurrentLocation);
super.onSaveInstanceState(outState);
}
}
/**
* Gets the device's current location and builds the map
* when the Google Play services client is successfully connected.
*/
@Override
public void onConnected(Bundle connectionHint) {
getDeviceLocation();
// Build the map.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Handles failure to connect to the Google Play services client.
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
// Refer to the reference doc for ConnectionResult to see what error codes might
// be returned in onConnectionFailed.
Log.d(TAG, "Play services connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
/**
* Handles suspension of the connection to the Google Play services client.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "Play services connection suspended");
}
/**
* Handles the callback when location changes.
*/
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateMarkers();
}
/**
* Manipulates the map when it's available.
* This callback is triggered when the map is ready to be used.
*/
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Add markers for nearby places.
updateMarkers();
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
/*
* Set the map's camera position to the current location of the device.
* If the previous state was saved, set the position to the saved state.
* If the current location is unknown, use a default position and zoom value.
*/
if (mCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
} else if (mCurrentLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
/**
* Builds a GoogleApiClient.
* Uses the addApi() method to request the Google Places API and the Fused Location Provider.
*/
private synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
createLocationRequest();
}
/**
* Sets up the location request.
*/
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
/*
* Sets the desired interval for active location updates. This interval is
* inexact. You may not receive updates at all if no location sources are available, or
* you may receive them slower than requested. You may also receive updates faster than
* requested if other applications are requesting location at a faster interval.
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
/*
* Sets the fastest rate for active location updates. This interval is exact, and your
* application will never receive updates faster than this value.
*/
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* Gets the current location of the device and starts the location update notifications.
*/
private void getDeviceLocation() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
* Also request regular updates about the device location.
*/
if (mLocationPermissionGranted) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
/**
* Handles the result of the request for location permissions.
*/
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
/**
* Adds markers for places nearby the device and turns the My Location feature on or off,
* provided location permission has been granted.
*/
private void updateMarkers() {
if (mMap == null) {
return;
}
if (mLocationPermissionGranted) {
// Get the businesses and other points of interest located
// nearest to the device's current location.
@SuppressWarnings("MissingPermission")
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
@Override
public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
// Add a marker for each place near the device's current location, with an
// info window showing place information.
String attributions = (String) placeLikelihood.getPlace().getAttributions();
String snippet = (String) placeLikelihood.getPlace().getAddress();
if (attributions != null) {
snippet = snippet + "\n" + attributions;
}
mMap.addMarker(new MarkerOptions()
.position(placeLikelihood.getPlace().getLatLng())
.title((String) placeLikelihood.getPlace().getName())
.snippet(snippet));
}
// Release the place likelihood buffer.
likelyPlaces.release();
}
});
} else {
mMap.addMarker(new MarkerOptions()
.position(mDefaultLocation)
.title(getString(R.string.default_info_title))
.snippet(getString(R.string.default_info_snippet)));
}
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
@SuppressWarnings("MissingPermission")
private void updateLocationUI() {
if (mMap == null) {
return;
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mCurrentLocation = null;
}
}
}
关于android - 如何在选项卡式 Activity 中的 SupportMapFragment 上设置标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41309530/
这个问题已经有答案了: Is there any way to accept only numeric values in a JTextField? (20 个回答) It's possible i
我使用戴尔 XPS M1710。笔记本电脑的盖子、侧面扬声器和前置扬声器都有灯(3 组灯可以单独调节)和鼠标垫下方的灯。在 BIOS 中,我可以更改这些灯的颜色,至少是每个组。另外,我可以在鼠标垫下打
我知道我可以使用 在 iOS 5 中打开设置应用 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"
我有一个 Django 应用程序,我正在尝试为其设置文档。目录结构如下: - doc - project | - manage.py 我已经设置了路径以便 Sphinx 可以看到东西,但是当我尝试使用
我正在使用 768mb ram 运行 centos 5.5。我一直在日志中获取 server reached MaxClients setting, consider raising the MaxC
我在具有以下配置的服务器内运行了 Drupal 安装: StartServers 5 MinSpareServers 5 MaxSpareServers 15 MaxClien
是否可以使用 Microsoft.Web.Administration 包为给定的 location 配置 asp 设置? 我想以编程方式将以下部分添加到本地 IIS applicationHost.
我一直在阅读为 kube-proxy 提供参数的文档,但没有解释应该如何使用这些参数。我使用 az aks create 创建我的集群使用 azure-cli 程序,然后我获得凭据并使用 kubect
我想知道与在 PHP 中使用 setcookie() 函数相比,在客户端通过 JavaScript 设置一些 cookie 是否有任何明显的优势?我能想到的唯一原因是减少一些网络流量(第一次)。但不是
我有一个按钮可以将 body class 设置为 .blackout 我正在使用 js-cookie设置cookie,下面的代码与我的按钮相关联。 $('#boToggle').on('click'
我有一堆自定义的 HTML div。我将其中的 3 存储在具有 slide 类的 div 中。然后,我使用该幻灯片类调用 slick 函数并应用如下设置: $('.slide').slick({
我正在创建一个应该在 Windows 8(桌面)上运行的应用 我需要: 允许用户使用我的应用启动“文件历史记录”。我需要找到打开“文件历史记录”的命令行。 我需要能够显示“文件历史记录”的当前设置。
我刚买了一台新的 MacBook Pro,并尝试在系统中设置 RVM。我安装了 RVM 并将默认设置为 ➜ rvm list default Default Ruby (for new shells)
由于有关 Firestore 中时间戳行为即将发生变化的警告,我正在尝试更改我的应用的初始化代码。 The behavior for Date objects stored in Firestore
在 ICS 中,网络 -> 数据使用设置屏幕中现在有“限制后台数据”设置。 有没有办法以编程方式为我的应用程序设置“限制后台数据”? 或 有没有办法为我的应用程序调出具有选项的“数据使用”设置? 最佳
我正在尝试使用 NextJS 应用程序设置 Jest,目前在 jest.config.js : module.exports = { testPathIgnorePatterns: ["/.n
我最近升级到 FlashDevelop 4,这当然已经将我之前的所有设置恢复到原来的状态。 我遇到的问题是我无法在新设置窗口的哪个位置找到关闭它在方括号、大括号等之前插入的自动空格的选项。 即它会自动
有没有办法以编程方式访问 iPhone/iPod touch 设置? 谢谢。比兰奇 最佳答案 大多数用户设置可以通过读取存储在 /User/Library/Preferences/ 中的属性列表来访问
删除某些值时,我需要选择哪些设置来维护有序队列。我创建了带有自动增量和主键的 id 的表。当我第一次插入值时,没问题。就像 1,2,3,4,5... 当删除某些值时,顺序会发生变化,例如 1,5,3.
我正在尝试设置示例 Symfony2 项目,如此处所示 http://symfony.com/doc/current/quick_tour/the_big_picture.html 在访问 confi
我是一名优秀的程序员,十分优秀!