我已经通过控制台打开了谷歌地图服务,并生成了一个调试密钥。
我已经调试过了,mMap 和mLocation 都不是空的。我可以成功获得纬度和经度。
但地图仍然是空白的。
请帮忙。
山姆
这是布局xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f2f5fa"
tools:context=".LocFm" >
<!-- top bar component -->
<ImageView
android:id="@+id/loc_topbar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:background="@drawable/topbar" />
<TextView
android:id="@+id/loc_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/loc_backBtn"
android:layout_centerHorizontal="true"
android:text="@string/loc_title"
android:textColor="#171717"
android:textSize="@dimen/title_font" />
<ImageView
android:id="@+id/loc_backBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="@drawable/backbtn" />
<!-- BODY -->
<FrameLayout android:id="@+id/map_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/loc_topbar"
android:layout_above="@+id/loc_bottombar"
>
<!-- Put fragments dynamically -->
</FrameLayout>
<!-- bottom bar component -->
<ImageView
android:id="@+id/loc_bottombar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="@drawable/bottombar" />
<Button
android:id="@+id/locBtn"
android:layout_width="@dimen/halfbutton_width"
android:layout_height="@dimen/halfbutton_height"
android:layout_alignTop="@+id/loc_bottombar"
android:layout_alignParentLeft="true"
android:layout_marginTop="@dimen/halfbutton_marginTop"
android:background="@drawable/halfbutton_bg"
android:text="@string/button_Loc"
android:textSize="@dimen/button_font"/>
<Button
android:id="@+id/loc_nextBtn"
android:layout_width="@dimen/halfbutton_width"
android:layout_height="@dimen/halfbutton_height"
android:layout_alignTop="@+id/loc_bottombar"
android:layout_alignParentRight="true"
android:layout_marginTop="@dimen/halfbutton_marginTop"
android:background="@drawable/halfbutton_bg"
android:text="@string/button_Continue"
android:textSize="@dimen/button_font"/>
<ImageView
android:id="@+id/nextImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/loc_nextBtn"
android:layout_alignTop="@+id/loc_nextBtn"
android:layout_marginRight="@dimen/buttonicon_marginRight"
android:layout_marginTop="@dimen/buttonicon_marginTop"
android:src="@drawable/next" />
<ImageView
android:id="@+id/locImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/locBtn"
android:layout_alignTop="@+id/locBtn"
android:layout_marginRight="@dimen/buttonicon_marginRight"
android:layout_marginTop="@dimen/buttonicon_marginTop"
android:src="@drawable/location" />
</RelativeLayout>
这是清单 xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.map.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/logo_icon"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my api key" />
<activity
android:name="com.example.map.LocFm"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name"
android:noHistory="true"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Java代码:
package com.example.map;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocFm extends FragmentActivity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
Timer positionTimer;
private GoogleMap mMap;
private Location mLocation;
private UiSettings mUiSettings;
private LocationClient mLocationClient;
private static SupportMapFragment mMapView;
private static final String MAP_FRAGMENT_TAG = "map";
public FragmentManager fManager;
double latitude, longitude, radius;
String sLat,sLong,sRange;
boolean bMaploaded=false;
int index =0;
int positionCount=0;
final int POSITION_COUNT_MAX=5;
final int POSITION_MIN=100;
final int PSSITION_MAX_TIMES=10;
OnlineHistoryInfo onLineHistory;
ProgressDialog dialog;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLocFm();
}
@Override
public void onLocationChanged(Location location) {
if (mLocationClient != null && mLocationClient.isConnected())
{
mLocation=mLocationClient.getLastLocation();
}
if (mLocation!=null)
{
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
radius=mLocation.getAccuracy();
sLat=Double.toString(latitude);
sLong=Double.toString(longitude);
sRange=Double.toString(radius);
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.addMarker(new MarkerOptions().position(latLng).title(getString(R.string.map_msg)));
}
positionCount++;
if(mLocationClient==null || radius<=POSITION_MIN)
{
mLocationClient.disconnect();
positionCount=0;
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setOnClickListener(this);
loc_nextBtn.setVisibility(View.VISIBLE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.VISIBLE);
showDialog(false,null);
}
if(positionCount>=POSITION_COUNT_MAX)
{
mLocationClient.disconnect();
positionCount=0;
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
@Override
public void onConnected(Bundle connectionHint) {
setUpMapIfNeeded();
position();
}
@Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private void mapDestroy()
{
if (mLocationClient != null)
mLocationClient.disconnect();
if(mMapView!=null){
FragmentTransaction ft = mMapView.getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(mMapView);
ft.commit();
}
if(mMap!=null)
{
mMap=null;
}
bMaploaded=false;
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the MapFragment.
mMap = mMapView.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
this,
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loc_backBtn:
mapDestroy();
LocFm.this.finish();
break;
case R.id.loc_nextBtn:
positionCount=0;
mapDestroy();
break;
case R.id.locBtn:
relocate();
break;
}
}
public void setLocFm(){
setContentView(R.layout.loc_fm);
loadMapFragment();
ImageView loc_backBtn=(ImageView)findViewById(R.id.loc_backBtn);
loc_backBtn.setOnClickListener(this);
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setVisibility(View.GONE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.GONE);
Button locBtn=(Button)findViewById(R.id.locBtn);
locBtn.setOnClickListener(this);
bMaploaded=true;
}
private void loadMapFragment() {
showDialog(true,getString(R.string.alert_postion));
// It isn't possible to set a fragment's id programmatically so we set a tag instead and
// search for it using that.
mMapView = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapView == null) {
// To programmatically add the map, we first create a SupportMapFragment.
mMapView = SupportMapFragment.newInstance();
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map_fragment, mMapView, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
}
setUpLocationClientIfNeeded();
if (!mLocationClient.isConnected()) mLocationClient.connect();
}
private void position()
{
showDialog(true,getString(R.string.alert_postion));
if (mMap != null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
mLocation = locationManager.getLastKnownLocation(provider);
mUiSettings = mMap.getUiSettings();
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
// Check if we were successful in obtaining the map.
mLocationClient.requestLocationUpdates(REQUEST,this); // LocationListener
}
}
public void relocate()
{
if (!mLocationClient.isConnected()) mLocationClient.connect();
WSWLog.i("relocate()");
}
/**
* @param dialgShow
*/
public void showDialog(boolean dialgShow,final String message)
{
WSWLog.i(" showDialog ("+dialgShow+","+message+")");
if(dialgShow)
{
if(dialog==null)
{
dialog = new ProgressDialog(this);
dialog.setCancelable(false);//false
{
dialog.setMessage(message);
}
}
else
{
dialog.setMessage(message);
}
dialog.show();
//
if(null != positionTimer)
{
positionTimer.cancel();
}
positionTimer= new Timer(true);
TimerTask task = new TimerTask(){
public void run() {
handler.sendEmptyMessage(1);
}
};
positionTimer.schedule(task,PSSITION_MAX_TIMES*1000, PSSITION_MAX_TIMES*1000);
}
else
{
if(null != positionTimer)
{
positionTimer.cancel();
}
if(dialog!=null)
{
dialog.dismiss();
}
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(null != positionTimer)
{
positionTimer.cancel();
}
showDialog(false,null);
//
alertNoPosition();
super.handleMessage(msg);
}
};
/**
*/
private void alertNoPosition()
{
AlertDialog.Builder builder = new Builder(this);
builder.setMessage(getString(R.string.loc_alert_realloc)); builder.setTitle(getString(R.string.button_Loc));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
LocFm.this.finish();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
relocate();
}
});
builder.create().show();
}
}