在google mapview上获取用户当前位置

时间:2012-10-10 17:03:55

标签: android google-maps api-key currentlocation

您好我一直试图找到并确定手机的位置(用户当前位置),但我没有运气。我希望有人能帮我解决这个问题。

只是添加一些,我收到“无法获取连接工厂客户端”错误。这是否与返回用户位置的能力有关?

如果有帮助的话,我一直在关注新波士顿的教程。

或者这与我的API密钥有关吗?但我可以正确接收地图,但无法确定用户的当前位置


主要代码:

public class Map extends MapActivity implements LocationListener{

MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;

LocationManager lm;
LocationListener ll;
String towers;
int lat = 0;
int longi = 0;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    map = (MapView)findViewById(R.id.mapview);
    map.setBuiltInZoomControls(true);

    touch t = new touch();
    overlayList = map.getOverlays();
    overlayList.add(t);
    compass = new MyLocationOverlay(Map.this, map);
    overlayList.add(compass);
    controller = map.getController();
    GeoPoint point = new GeoPoint(832332,4121093);
    controller.animateTo(point);
    controller.setZoom(8);


    d = getResources().getDrawable(R.drawable.pointer);

    //placing location
    lm =(LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria crit = new Criteria();
    towers = lm.getBestProvider(crit, false);
    Location loc = lm.getLastKnownLocation(towers);

    if(loc != null){
        lat = (int) (loc.getLatitude() *1E6);
        longi = (int)(loc.getLongitude()*1E6);
        GeoPoint location = new GeoPoint(lat, longi);
        OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
        CustomPinPoint custom = new CustomPinPoint(d, Map.this);
        custom.insertPinPoint(overlayitem);
        overlayList.add(custom);

    }else{
        Toast.makeText(Map.this, "Location is null", Toast.LENGTH_LONG).show();
        lm.requestLocationUpdates(towers, 1500, 1, this);
    }


}


@Override
protected void onPause() {
    // TODO Auto-generated method stub
    compass.disableCompass();
    super.onPause();
    lm.removeUpdates(this);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    compass.enableCompass();
    super.onResume();
    lm.requestLocationUpdates(towers, 500, 1, this);

 }

我认为你可以忽略alertdialog

public class touch extends Overlay {

    public boolean onTouchEvent(MotionEvent e, MapView m){
        if(e.getAction()== MotionEvent.ACTION_DOWN){
            start = e.getEventTime();
            x = (int) e.getX();
            y = (int) e.getY();
            touchedPoint = map.getProjection().fromPixels(x, y);

        }
        if(e.getAction()== MotionEvent.ACTION_UP){
            stop = e.getEventTime();
        }
        if(stop-start >1200){
            AlertDialog alert = new AlertDialog.Builder(Map.this).create();
            alert.setTitle("Option");
            alert.setMessage("Pick the option");
            alert.setCanceledOnTouchOutside(true);
            alert.setButton("Place pointer pinpoint", 
                    new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                    OverlayItem overlayitem = new OverlayItem(touchedPoint , "wassup", "2nd string");
                    CustomPinPoint custom = new CustomPinPoint(d, Map.this);
                    custom.insertPinPoint(overlayitem);
                    overlayList.add(custom);

                }
            });

            alert.setButton2("Get address", 
                    new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                    Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
                        try{
                            List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6()
                                    /1E6, touchedPoint.getLongitudeE6() /1E6, 1);

                            if (address.size()>0){
                                String display = "";

                                for(int i=0 ; i<address.get(0).getMaxAddressLineIndex(); i++){
                                    display +=address.get(0).getAddressLine(i) + "\n";
                                }
                                Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
                                t.show();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }finally{

                        }
                }
            });

            alert.setButton3("Toggle View", 
                    new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                    if(map.isSatellite()){
                        map.setSatellite(false);
                        map.setStreetView(true);
                    }else{
                        map.setStreetView(false);
                        map.setSatellite(true);
                    }

                }
            });

            alert.show();
            return true;


        }
        return false;

    }

}




@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_map, menu);
    return true;
}


@Override
public void onLocationChanged(Location l) {
    // TODO Auto-generated method stub
    lat = (int)(l.getLatitude()*1E6);
    longi = (int)(l.getLongitude()*1E6);
    GeoPoint location = new GeoPoint(lat, longi);
    OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
    CustomPinPoint custom = new CustomPinPoint(d, Map.this);
    custom.insertPinPoint(overlayitem);
    overlayList.add(custom);

}


@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}


@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}


 }

CustomPinPoint代码:

public class CustomPinPoint extends ItemizedOverlay<OverlayItem> {

private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;

//  tesst google code
public CustomPinPoint(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));
    // TODO Auto-generated constructor stub
}

public CustomPinPoint(Drawable defaultMarker, Context context) {
    // TODO Auto-generated constructor stub
    this(defaultMarker);  //original code


}

@Override
protected OverlayItem createItem(int i) {
    // TODO Auto-generated method stub
    return pinpoints.get(i);

}

@Override
public int size() {
    // TODO Auto-generated method stub
    return pinpoints.size();
}

public void insertPinPoint(OverlayItem item){
    pinpoints.add(item);
//  this.populate(); //  original code
//  test code
    populate();
}

@Override
protected boolean onTap(int index){
    OverlayItem item = pinpoints.get(index);
    AlertDialog.Builder dialog = new AlertDialog.Builder(c);
    dialog.setTitle(item.getTitle());
    dialog.setMessage(item.getSnippet());
    dialog.show();
    return true;

}

public void addOverlay(OverlayItem overlay) {
    // TODO Auto-generated method stub
    pinpoints.add(overlay);
    populate();
}



    }

XML代码:

         <com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:id="@+id/mapview"
             android:enabled="true"
             android:clickable="true"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:apiKey="0t9rHfGlUPgisa8P9MRAsSxhRXTVCL0XJog7uiA"
             />

2 个答案:

答案 0 :(得分:2)

以下是如何轻松完成此操作的示例,尝试将此逻辑实现到您的项目中:

public class MyMapActivity extends MapActivity {
private MapView map;
private MapController controller;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mymap);
    initMapView();
    initMyLocation();

            map.invalidate();
}

    private void initMapView() {
    map = (MapView) findViewById(R.id.map);
    controller = map.getController();
    map.setSatellite(true);
    map.setBuiltInZoomControls(true);
}
private void initMyLocation() {
    final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
    overlay.enableMyLocation();
    //overlay.enableCompass(); // does not work in emulator
    overlay.runOnFirstFix(new Runnable() {
        public void run() {
            // Zoom in to current location
            controller.setZoom(15);
            controller.animateTo(overlay.getMyLocation());
    }});
}

}

答案 1 :(得分:0)

这是令人尴尬的,事实证明我的代码是正确的,问题是设备的GPS没有打开。好吧,我希望我的代码可以帮助任何有需要的人。干杯!