愿君学长松,慎勿作桃李。这篇文章主要讲述Map返回Null或空Android Studio相关的知识,希望能为你提供帮助。
我是android新手编程,需要制作一个GPS应用程序,我创建了一个带有图形界面的小应用程序进行测试,但我没有成就做地图工作,这返回null,我无法解决这个问题。当我认为休息时,我会留下我的代码。谢谢
<
?xml version="1.0" encoding="utf-8"?>
<
manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="co.quindio.sena.ejemplomaparutas">
<
!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<
application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<
activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<
intent-filter>
<
action android:name="android.intent.action.MAIN" />
<
category android:name="android.intent.category.LAUNCHER" />
<
/intent-filter>
<
/activity>
<
!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<
meta-data
android:name="com.google.android.geo.API_KEY"
android:value="https://www.songbingjia.com/android/@string/google_maps_key" />
<
activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<
/activity>
<
/application>
<
/manifest>
公共类MapsActivity扩展FragmentActivity实现OnMapReadyCallback {
private GoogleMap mMap;
Double latInicial,longInicial,latFinal,longFinal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
/////////////
LatLng center = null;
ArrayList<
LatLng>
points = null;
PolylineOptions lineOptions = null;
// setUpMapIfNeeded();
// recorriendo todas las rutas
for(int i=0;
i<
Utilidades.routes.size();
i++){
points = new ArrayList<
LatLng>
();
lineOptions = new PolylineOptions();
// Obteniendo el detalle de la ruta
List<
HashMap<
String, String>
>
path = Utilidades.routes.get(i);
// Obteniendo todos los puntos y/o coordenadas de la ruta
for(int j=0;
j<
path.size();
j++){
HashMap<
String,String>
point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
if (center == null) {
//Obtengo la 1ra coordenada para centrar el mapa en la misma.
center = new LatLng(lat, lng);
}
points.add(position);
}// Agregamos todos los puntos en la ruta al objeto LineOptions
lineOptions.addAll(points);
//Definimos el grosor de las Polilíneas
lineOptions.width(2);
//Definimos el color de la Polilíneas
lineOptions.color(Color.BLUE);
}// Dibujamos las Polilineas en el Google Map para cada ruta
mMap.addPolyline(lineOptions);
LatLng origen = new LatLng(Utilidades.coordenadas.getLatitudInicial(), Utilidades.coordenadas.getLongitudInicial());
mMap.addMarker(new MarkerOptions().position(origen).title("Lat: "+Utilidades.coordenadas.getLatitudInicial()+" - Long: "+Utilidades.coordenadas.getLongitudInicial()));
LatLng destino = new LatLng(Utilidades.coordenadas.getLatitudFinal(), Utilidades.coordenadas.getLongitudFinal());
mMap.addMarker(new MarkerOptions().position(destino).title("Lat: "+Utilidades.coordenadas.getLatitudFinal()+" - Long: "+Utilidades.coordenadas.getLongitudFinal()));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(center, 15));
/////////////
}
}
<
fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="co.quindio.sena.ejemplomaparutas.MapsActivity" />
[https://i.stack.imgur.com/pzeuy.png这是错误]
package co.quindio.sena.ejemplomaparutas;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.model.LatLng;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {EditText txtLatInicio,txtLongInicio,txtLatFinal,txtLongFinal;
JsonObjectRequest jsonObjectRequest;
RequestQueue request;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
txtLatInicio= (EditText) findViewById(R.id.txtLatIni);
txtLongInicio= (EditText) findViewById(R.id.txtLongIni);
txtLatFinal= (EditText) findViewById(R.id.txtLatFin);
txtLongFinal= (EditText) findViewById(R.id.txtLongFin);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Utilidades.coordenadas.setLatitudInicial(Double.valueOf(txtLatInicio.getText().toString()));
Utilidades.coordenadas.setLongitudInicial(Double.valueOf(txtLongInicio.getText().toString()));
Utilidades.coordenadas.setLatitudFinal(Double.valueOf(txtLatFinal.getText().toString()));
Utilidades.coordenadas.setLongitudFinal(Double.valueOf(txtLongFinal.getText().toString()));
webServiceObtenerRuta(txtLatInicio.getText().toString(),txtLongInicio.getText().toString(),
txtLatFinal.getText().toString(),txtLongFinal.getText().toString());
Intent miIntent=new Intent(MainActivity.this, MapsActivity.class);
startActivity(miIntent);
}
});
request= Volley.newRequestQueue(getApplicationContext());
}private void webServiceObtenerRuta(String latitudInicial, String longitudInicial, String latitudFinal, String longitudFinal) {String url="https://maps.googleapis.com/maps/api/directions/json?origin="+latitudInicial+","+longitudInicial
+"&
destination="+latitudFinal+","+longitudFinal;
jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<
JSONObject>
() {
@Override
public void onResponse(JSONObject response) {
//Este método PARSEA el JSONObject que retorna del API de Rutas de Google devolviendo
//una lista del lista de HashMap Strings con el listado de Coordenadas de Lat y Long,
//con la cual se podrá dibujar pollinas que describan la ruta entre 2 puntos.
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {jRoutes = response.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;
i<
jRoutes.length();
i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List<
HashMap<
String, String>
>
path = new ArrayList<
HashMap<
String, String>
>
();
/** Traversing all legs */
for(int j=0;
j<
jLegs.length();
j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;
k<
jSteps.length();
k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<
LatLng>
list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;
l<
list.size();
l++){
HashMap<
String, String>
hm = new HashMap<
String, String>
();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
Utilidades.routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No se puede conectar "+error.toString(), Toast.LENGTH_LONG).show();
System.out.println();
Log.d("ERROR: ", error.toString());
}
}
);
request.add(jsonObjectRequest);
}public List<
List<
HashMap<
String,String>
>
>
parse(JSONObject jObject){
//Este método PARSEA el JSONObject que retorna del API de Rutas de Google devolviendo
//una lista del lista de HashMap Strings con el listado de Coordenadas de Lat y Long,
//con la cual se podrá dibujar pollinas que describan la ruta entre 2 puntos.
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;
i<
jRoutes.length();
i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List<
HashMap<
String, String>
>
path = new ArrayList<
HashMap<
String, String>
>
();
/** Traversing all legs */
for(int j=0;
j<
jLegs.length();
j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;
k<
jSteps.length();
k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<
LatLng>
list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;
l<
list.size();
l++){
HashMap<
String, String>
hm = new HashMap<
String, String>
();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
Utilidades.routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return Utilidades.routes;
}public void onClick(View view) {if (view.getId()==R.id.btnObtenerCoordenadas){
// txtLatInicio.setText("4.543986");
txtLongInicio.setText("-75.666736");
txtLatInicio.setText("-34.616516");
txtLongInicio.setText("-58.555252");
//Unicentro
//txtLatFinal.setText("4.540026");
txtLongFinal.setText("-75.665479");
txtLatFinal.setText("-34.604833");
txtLongFinal.setText("-58.564333");
//Parque del café
//txtLatFinal.setText("4.541396");
txtLongFinal.setText("-75.771741");
}}private List<
LatLng>
decodePoly(String encoded) {List<
LatLng>
poly = new ArrayList<
LatLng>
();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index <
len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b &
0x1f) <
<
shift;
shift += 5;
} while (b >
= 0x20);
int dlat = ((result &
1) != 0 ? ~(result >
>
1) : (result >
>
1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b &
0x1f) <
<
shift;
shift += 5;
} while (b >
= 0x20);
int dlng = ((result &
1) != 0 ? ~(result >
>
1) : (result >
>
1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}return poly;
}@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu;
this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}return super.onOptionsItemSelected(item);
}}package co.quindio.sena.ejemplomaparutas;
/**
* Created by CHENAO on 29/07/2018.
*/public class Punto {private Double latitudInicial;
private Double longitudInicial;
private Double latitudFinal;
private Double longitudFinal;
public Double getLatitudInicial() {
return latitudInicial;
}public void setLatitudInicial(Double latitudInicial) {
this.latitudInicial = latitudInicial;
}public Double getLongitudInicial() {
return longitudInicial;
}public void setLongitudInicial(Double longitudInicial) {
this.longitudInicial = longitudInicial;
}public Double getLatitudFinal() {
return latitudFinal;
}public void setLatitudFinal(Double latitudFinal) {
this.latitudFinal = latitudFinal;
}public Double getLongitudFinal() {
return longitudFinal;
}public void setLongitudFinal(Double longitudFinal) {
this.longitudFinal = longitudFinal;
}
}package co.quindio.sena.ejemplomaparutas;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by CHENAO on 25/08/2018.
*/public class Utilidades {
public static List<
List<
HashMap<
String, String>
>
>
routes = new ArrayList<
List<
HashMap<
String,String>
>
>
();
public static Punto coordenadas=new Punto();
}
答案
<
!--Did you getgoogle map api key? If not then Follow this. get thegoogle map api key and paste into "res/values/google_maps_api.xml"-->
<
resources>
<
!-- TODO: Before you run your application, you need a Google Maps API key.
See this page for more information:
https://developers.google.com/maps/documentation/android/start#get_an_android_certificate_and_the_google_maps_api_key
Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
Note: This resource is used for the debug build target. Update this file if you just want to run
the demo app.
-->
<
string name="google_maps_key" translatable="false" templateMergeStrategy="preserve">
YOUR_KEY_HERE
<
/string>
另一答案首先将
<
uses-permission android:name="android.permission.INTERNET" />
放在AndroidManifest.xml中。build.gradle(在应用程序级别)中您的游戏服务依赖项是什么?
【Map返回Null或空Android Studio】检查:
//play services
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
推荐阅读
- 如何在Android上以编程方式启用或禁用GPS()
- Android GPS FusedLocationProviderClient(经度错误)
- 如何在Android 6.x上以编程方式启用或禁用GPS()
- 有没有办法清除已经从Android设备手动捕获的位置详细信息()
- 如何在Android中使用GPS服务
- 如何在android中将输入流转换为字节数组到字符串
- Android studio - 无法连接到LDAP服务器
- 用户杀死Android应用后保存状态
- Android中TextView的TextAppearance属性