MainActivity.java
package com.example.neetu.mapexample;
import android.app.ActionBar;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
EditText etLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Button btn_find = (Button) findViewById(R.id.btn_find);
etLocation = (EditText) findViewById(R.id.et_location);
View.OnClickListener findClickListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String location = etLocation.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
}
};
btn_find.setOnClickListener(findClickListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onMapReady(GoogleMap googleMap)
{
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>
{
@Override
protected List<Address> doInBackground(String... locationName)
{
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(MainActivity.this, (CharSequence) addresses, Toast.LENGTH_SHORT).show();
return addresses;
}
@Override
protected void onPostExecute(List<Address> addresses)
{
if(addresses==null || addresses.size()==0)
{
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
//googleMap.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
Toast.makeText(MainActivity.this, addressText, Toast.LENGTH_SHORT).show();
googleMap.addMarker(new MarkerOptions().position(latLng).title(addressText));
if(i==0)
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_btn_find"
android:layout_alignParentRight="true" />
<EditText
android:id="@+id/et_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="@string/hnt_et_location"
android:layout_toLeftOf="@id/btn_find" />
</RelativeLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
安卓清单.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.neetu.mapexample">
<!--
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.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<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="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps"></activity>
</application>
</manifest>
我尝试在编辑中通过输入地名来标记和显示该地点 文本,但此处发生错误。请帮助我。
日志猫:
java.lang.NullPointerException: Try to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions(' 在空对象引用上 在 com.example.neetu.mapexample.MainActivity$GeocoderTask.onPostExecute(MainActivity.java:119( 在 com.example.neetu.mapexample.MainActivity$GeocoderTask.onPostExecute(MainActivity.java:73(
这是因为您尚未为googleMap
字段分配值。准备就绪后更新其值。
@Override
public void onMapReady(GoogleMap googleMap){
this.googleMap = googleMap;
}
还要在点击侦听器中添加googleMap != null
连续性。
if(googleMap!=null && location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}