我正在尝试在应用程序中使用HERE映射。但是,当尝试以“片段”视图查看地图时,似乎有些困难。当地图显示在我的主要活动中时,没有发生此问题。
我以these个示例为基础。在活动中使用时效果很好。
我没有查看this线程。
您可能会找到我的代码的简化版本,该代码应该可以在下面的地图中查看:
主要活动类别:
package com.example.heremapapplication;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.here.android.mpa.common.ApplicationContext;
public class MainActivity extends AppCompatActivity {
MapFragmentView mapFragmentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
initiateMap();
}
public void initiateMap() {
//Start map
mapFragmentView = new MapFragmentView();
mapFragmentView.setM_activity(this);
ApplicationContext applicationContext = new ApplicationContext(getApplicationContext());
mapFragmentView.initMapFragment(applicationContext, this);
getSupportFragmentManager().beginTransaction().replace(R.id.frameLayoutMapView, mapFragmentView).commit();
}
}
MapFragmentView片段:
package com.example.heremapapplication;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.here.android.mpa.common.ApplicationContext;
import com.here.android.mpa.common.GeoCoordinate;
import com.here.android.mpa.common.MapEngine;
import com.here.android.mpa.common.OnEngineInitListener;
import com.here.android.mpa.common.PositioningManager;
import com.here.android.mpa.mapping.Map;
import com.here.android.mpa.mapping.MapView;
import java.io.File;
public class MapFragmentView extends Fragment {
private AppCompatActivity m_activity;
private PositioningManager positioningManager;
private MapEngine mapEngine = MapEngine.getInstance();
private MapView mapView;
private static View v;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
try {
v = inflater.inflate(R.layout.map_fragment, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
return v;
}
public MapFragmentView() {
}
private Map map;
public void initMapFragment(ApplicationContext applicationContext, Context context) {
/* Locate the mapFragment UI element */
mapView = new MapView(context);
// Set path of isolated disk cache
String diskCacheRoot = Environment.getExternalStorageDirectory().getPath()
+ File.separator + ".isolated-here-maps";
// Retrieve intent name from manifest
String intentName = "";
try {
ApplicationInfo ai = m_activity.getPackageManager().getApplicationInfo(m_activity.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
intentName = bundle.getString("INTENT_NAME");
} catch (PackageManager.NameNotFoundException e) {
Log.e(this.getClass().toString(), "Failed to find intent name, NameNotFound: " + e.getMessage());
}
boolean success = com.here.android.mpa.common.MapSettings.setIsolatedDiskCacheRootPath(diskCacheRoot, intentName);
if (!success) {
// Setting the isolated disk cache was not successful, please check if the path is valid and
// ensure that it does not match the default location
// (getExternalStorageDirectory()/.here-maps).
// Also, ensure the provided intent name does not match the default intent name.
} else {
if (mapView != null) {
System.out.println("hop buraya girildi!");
/* Initialize the SupportMapFragment, results will be given via the called back. m_mapFragment.init(context,new OnEngineInitListener() */
mapEngine.init(applicationContext, new OnEngineInitListener() {
@Override
public void onEngineInitializationCompleted(OnEngineInitListener.Error error) {
if (error == Error.NONE) {
positioningManager = PositioningManager.getInstance();
positioningManager.start(PositioningManager.LocationMethod.GPS_NETWORK_INDOOR);
map = mapView.getMap();
GeoCoordinate myCurrentPosition = positioningManager.getPosition().getCoordinate();
} else {
Toast.makeText(m_activity,
"ERROR: Cannot initialize Map with error " + error,
Toast.LENGTH_LONG).show();
}
}
});
}
}
}
public void setM_activity(AppCompatActivity m_activity) {
this.m_activity = m_activity;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frameLayoutMapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
</RelativeLayout>
map_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapFragment"
android:name="com.here.android.mpa.mapping.MapFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
运行该程序后,我们应该能够在屏幕上查看HEREmap。但是它没有出现。 我们看到一个白色的屏幕。而且,如果我们要在后台发送该应用,屏幕将变黑。
非常感谢!
答案 0 :(得分:1)
进一步查看了医学博士的response之后,我终于设法以片段视图查看了地图。
您可以在下面找到我的解决方案:
主要活动:
package com.example.heremapapplication;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.here.android.mpa.common.ApplicationContext;
public class MainActivity extends AppCompatActivity {
MapFragmentView mapFragmentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
initiateMap();
}
public void initiateMap() {
//Start map
mapFragmentView=new MapFragmentView();
getSupportFragmentManager().beginTransaction().replace(R.id.frameLayoutMapView, mapFragmentView).commit();
}
}
MapFragmentView片段:
/*
* Copyright (c) 2011-2019 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.heremapapplication;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.here.android.mpa.common.ApplicationContext;
import com.here.android.mpa.common.GeoCoordinate;
import com.here.android.mpa.common.MapEngine;
import com.here.android.mpa.common.OnEngineInitListener;
import com.here.android.mpa.common.PositioningManager;
import com.here.android.mpa.mapping.Map;
import com.here.android.mpa.mapping.MapFragment;
import com.here.android.mpa.mapping.MapView;
import java.io.File;
/**
* This class encapsulates the properties and functionality of the Map view.It also implements 4
* types of discovery requests that HERE Android SDK provides as example.
*/
public class MapFragmentView extends Fragment {
private Activity m_activity;
private PositioningManager positioningManager;
private MapEngine mapEngine = MapEngine.getInstance();
private MapView mapView;
private static View v;
private MapFragment mapFragmentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("onCreateView Çağrıldı");
v = inflater.inflate(R.layout.map_frame, container, false);
mapFragmentView = new MapFragment();
FragmentManager fm = m_activity.getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout,mapFragmentView).commit();
//Here cinsinden ApplicationContext yarattık aşağıda:
com.here.android.mpa.common.ApplicationContext newContext =new ApplicationContext(m_activity);
//O yarttığımız contexti MapFragmentView.init methodu için kullandık (Mine de vardı ;) ):
mapFragmentView.init(newContext, new OnEngineInitListener() {
@Override
public void onEngineInitializationCompleted(Error error) {
if (error == Error.NONE) {
map = mapFragmentView.getMap();
} else {
Toast.makeText(m_activity,
"ERROR: Cannot initialize Map with error " + error,
Toast.LENGTH_LONG).show();
}
}
});
return v;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(m_activity);
System.out.println("ONETEŞ");
try {
m_activity = (AppCompatActivity) activity;
//mCallbacks = (MyNavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
System.out.println("ONETEŞ SIKINTI");
}
}
public MapFragmentView() {
}
private Map map;
public void initMapFragment() {
Context context =getContext();
ApplicationContext appContext = new ApplicationContext(context);
/* Locate the mapFragment UI element */
mapView = new MapView(context);
System.out.println("Application context bu: "+appContext.getClass().toString());
// Set path of isolated disk cache
String diskCacheRoot = Environment.getExternalStorageDirectory().getPath()
+ File.separator + ".isolated-here-maps";
// Retrieve intent name from manifest
String intentName = "";
try {
ApplicationInfo ai = m_activity.getPackageManager().getApplicationInfo(m_activity.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
intentName = bundle.getString("INTENT_NAME");
} catch (PackageManager.NameNotFoundException e) {
Log.e(this.getClass().toString(), "Failed to find intent name, NameNotFound: " + e.getMessage());
}
boolean success = com.here.android.mpa.common.MapSettings.setIsolatedDiskCacheRootPath(diskCacheRoot, intentName);
if (!success) {
// Setting the isolated disk cache was not successful, please check if the path is valid and
// ensure that it does not match the default location
// (getExternalStorageDirectory()/.here-maps).
// Also, ensure the provided intent name does not match the default intent name.
} else {
if (mapView != null) {
/* Initialize the SupportMapFragment, results will be given via the called back. m_mapFragment.init(context,new OnEngineInitListener() */
mapEngine.init(appContext, new OnEngineInitListener() {
@Override
public void onEngineInitializationCompleted(OnEngineInitListener.Error error) {
if (error == Error.NONE) {
positioningManager = PositioningManager.getInstance();
positioningManager.start(PositioningManager.LocationMethod.GPS_NETWORK_INDOOR);
map = mapView.getMap();
GeoCoordinate myCurrentPosition = positioningManager.getPosition().getCoordinate();
} else {
Toast.makeText(m_activity,
"ERROR: Cannot initialize Map with error " + error,
Toast.LENGTH_LONG).show();
}
}
});
}
}
}
public void setM_activity(AppCompatActivity m_activity) {
this.m_activity = m_activity;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frameLayoutMapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
</RelativeLayout>
map_frame.xml
我们已将地图片段转换为框架
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayoutForMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
答案 1 :(得分:1)
我找到了一个干净方便的解决方案,可以在这里从一个片段中使用地图,实际上,在我的项目中,默认情况下,我使用Navigation Drawer Activity,并且使用其中一个片段放置地图,我共享代码是因为我花了很多精力来提取它
class GalleryFragment : Fragment() {
private lateinit var galleryViewModel: GalleryViewModel
/**
* permissions request code
*/
private val REQUEST_CODE_ASK_PERMISSIONS = 1
/**
* Permissions that need to be explicitly requested from end user.
*/
private val REQUIRED_SDK_PERMISSIONS = arrayOf<String>(
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE
)
private var map: Map? = null
// map fragment embedded in this activity
private lateinit var mapFragment: AndroidXMapFragment
private var initialitation : Boolean = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
checkPermissions()
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_gallery, container, false)
if(initialitation){
mapFragment = childFragmentManager.findFragmentById(R.id.mapfragment) as AndroidXMapFragment
mapFragment.init {
if(it == OnEngineInitListener.Error.NONE){
map = mapFragment.map
map!!.setCenter(
GeoCoordinate(49.196261, -123.004773, 0.0),
Map.Animation.NONE)
map!!.zoomLevel = (map!!.maxZoomLevel + map!!.minZoomLevel) / 2
}else{
Log.e(TAG,"Error al inicializar el mapa")
}
}
}
return root
}
/**
* Checks the dynamically-controlled permissions and requests missing permissions from end user.
*/
protected fun checkPermissions() {
val missingPermissions: MutableList<String> = ArrayList()
// check all required dynamic permissions
for (permission in REQUIRED_SDK_PERMISSIONS) {
val result = ContextCompat.checkSelfPermission(requireActivity(), permission)
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission)
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
val permissions = missingPermissions
.toTypedArray()
ActivityCompat.requestPermissions(
requireActivity(),
permissions,
REQUEST_CODE_ASK_PERMISSIONS
)
} else {
val grantResults = IntArray(REQUIRED_SDK_PERMISSIONS.size)
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED)
onRequestPermissionsResult(
REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) {
REQUEST_CODE_ASK_PERMISSIONS -> {
var index = permissions.size - 1
while (index >= 0) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(
activity, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG
).show()
requireActivity().finish()
return
}
--index
}
// all permissions were granted
initialitation = true
}
}
}
}
这是我使用的XML片段
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.gallery.GalleryFragment">
<fragment
android:id="@+id/mapfragment"
class="com.here.android.mpa.mapping.AndroidXMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
希望它对您或遇到相同问题的人有帮助
答案 2 :(得分:0)
通常,如果您在布局文件中定义com.here.android.mpa.mapping.MapFragment,则应直接将其直接用于地图初始化,而不要使用'MapView'/ MapEngine,请查看以下示例:{ {3}}
在您的代码中也应使用类似的内容
private SupportMapFragment getMapFragment() {
return (SupportMapFragment) m_activity.getSupportFragmentManager().findFragmentById(R.id.mapfragment);
}
/* Locate the mapFragment UI element */
m_mapFragment = getMapFragment();
// Set path of isolated disk cache
String diskCacheRoot = Environment.getExternalStorageDirectory().getPath()
+ File.separator + ".isolated-here-maps";
// Retrieve intent name from manifest
String intentName = "";
try {
ApplicationInfo ai = m_activity.getPackageManager().getApplicationInfo(m_activity.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
intentName = bundle.getString("INTENT_NAME");
} catch (PackageManager.NameNotFoundException e) {
Log.e(this.getClass().toString(), "Failed to find intent name, NameNotFound: " + e.getMessage());
}
boolean success = com.here.android.mpa.common.MapSettings.setIsolatedDiskCacheRootPath(diskCacheRoot, intentName);
if (!success) {
// Setting the isolated disk cache was not successful, please check if the path is valid and
// ensure that it does not match the default location
// (getExternalStorageDirectory()/.here-maps).
// Also, ensure the provided intent name does not match the default intent name.
} else {
if (m_mapFragment != null) {
/* Initialize the SupportMapFragment, results will be given via the called back. */
m_mapFragment.init(new OnEngineInitListener() {
......