如何使用mapview显示地图

时间:2014-04-21 10:54:41

标签: android google-maps

AndroidGoogleMapsActivity.java

    import java.util.List;

    import android.graphics.drawable.Drawable;
    import android.os.Bundle;

    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;
    import com.google.android.maps.Overlay;
    import com.google.android.maps.OverlayItem;

    public class AndroidGoogleMapsActivity extends MapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Displaying Zooming controls
    MapView mapView = (MapView) findViewById(R.id.mapView);
    mapView.setBuiltInZoomControls(true);

    /**
     * Changing Map Type
     * */
    mapView.setSatellite(true); // Satellite View
    // mapView.setStreetView(true); // Street View
    // mapView.setTraffic(true); // Traffic view

    /**
     * showing location by Latitude and Longitude
     * */        
    MapController mc = mapView.getController();
    double lat = Double.parseDouble("48.85827758964043");
    double lon = Double.parseDouble("2.294543981552124");
    GeoPoint geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
    mc.animateTo(geoPoint);
    // Uri location = Uri.parse("geo:0,0?q="+(lat * 1E6)+","+(lon * 1E6));
    /* Uri location = Uri.parse("geo:0,0?q="+(geoPoint));

     Intent intent = new Intent(Intent.ACTION_VIEW, location);
    //intent.setPackage(defaultGpsPackage);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);*/
    mc.setZoom(15);
    mapView.invalidate(); 


    /**
     * Placing Marker
     * */
    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
    AddItemizedOverlay itemizedOverlay = 
         new AddItemizedOverlay(drawable, this);


    OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");

    itemizedOverlay.addOverlay(overlayitem);
    mapOverlays.add(itemizedOverlay);

   }

@Override
protected boolean isRouteDisplayed() {
    return false;
}
    }

AddItemizedOverlay.java

    import java.util.ArrayList;
    import android.content.Context;
    import android.graphics.drawable.Drawable;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.widget.Toast;
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.ItemizedOverlay;
    import com.google.android.maps.MapView;
    import com.google.android.maps.OverlayItem;

    public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {

private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();

private Context context;

public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}

public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}

@Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}

@Override
public int size() {
return mapOverlays.size();
}

@Override
protected boolean onTap(int index) {
Log.e("Tap", "Tap Performed");
return true;
}

public void addOverlay(OverlayItem overlay) {
    mapOverlays.add(overlay);
this.populate();
}
@Override
    public boolean onTouchEvent(MotionEvent event, MapView mapView) 
    {   

    if (event.getAction() == 1) {                
    GeoPoint geopoint = mapView.getProjection().fromPixels(
    (int) event.getX(),
    (int) event.getY());
    // latitude
    double lat = geopoint.getLatitudeE6() / 1E6;
    // longitude
    double lon = geopoint.getLongitudeE6() / 1E6;
    Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
    }                            
    return false;
    } 

}

main.xml中

    <?xml version="1.0" encoding="utf-8"?>
    <com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="AIzaSyCgSK8QeqICTwIYuxkx2TAixqjePsaf01o"
    />

的manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.googlemaps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" 
    android:targetSdkVersion="16"/>

    <uses-permission  android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission  android:name="android.permission.INTERNET"/>
    <uses-permission  android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    <!--  Add Google Map Library -->
    <uses-library android:name="com.google.android.maps" />

    <activity
    android:label="@string/app_name"
    android:name=".AndroidGoogleMapsActivity" >
    <intent-filter >
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    </application>   

    </manifest>

我需要显示地图。但是使用此代码我只得到网格视图和纬度和经度值。任何人请告诉我我应该在这里使用mapview显示地图的更正

3 个答案:

答案 0 :(得分:1)

您知道GoogleMapV1已经被删除了吗?

来自文档:

  

注意:截至2012年12月3日,Google Maps Android API版本1已正式弃用。这意味着从2013年3月18日起,您将无法再申请API密钥这个版本。 Google Maps Android API v1不会添加任何新功能。但是,使用v1的应用程序将继续在设备上运行。鼓励现有和新开发人员使用Google Maps Android API v2。

因此,您将无法再使用GoogleMapV1来使用地图。您必须切换到GoogleMapV2并实施它才能加载地图。

答案 1 :(得分:0)

请参阅此link,因为它提供了一个很好的教程来实现谷歌地图v2 ..

以下是显示google maps v2 ..

的完整代码

activity_main.xml中

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.movingmarkergooglemaps.MainActivity"
tools:ignore="MergeRootFrame" >

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_width="fill_parent"
    android:layout_height="match_parent" />

MainActivity.java

package com.example.movingmarkergooglemaps;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity{

GoogleMap Mmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();

    }
    gps=new GPSTracker(MainActivity.this);
    Mmap=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {


    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);

        return rootView;
    }
}
}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <uses-library android:name="com.google.android.maps" />
    <activity
        android:name="com.example.movingmarkergooglemaps.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="**Replace with your key**" />
</application>

不要忘记添加google-play-services_lib

答案 2 :(得分:0)

我正在发布我的Java类和xml。只需将其加载到您的项目中即可。希望对你有效。我花了很多时间来找到这个确切的解决方案。

java文件:

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {

    private TextView lblLocation;
    private MapView mapView;
    private GoogleMap map;
    private GPSTracker gpsTracker;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_location_on_map);
        mapView = (MapView) findViewById(R.id.idLocationMap);
        lblLocation = (TextView) findViewById(R.id.idLocationText);
        gpsTracker = new GPSTracker(this);
        if (mapView != null) {
            mapView.onCreate(savedInstanceState);
            mapView.getMapAsync(this);
        }
        Log.d("location is : ", gpsTracker.getLatitude() + " and " + gpsTracker.getLongitude());
        lblLocation.setText(gpsTracker.getAddressLine(MapActivity.this));
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        MapsInitializer.initialize(getApplicationContext());
        //LatLng class is google provided class to get latiude and longitude of location.
        //GpsTracker is helper class to get the details for current location latitude and longitude.
        LatLng location = new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude());
        map = googleMap;
        map.addMarker(new MarkerOptions().position(location).title("Marker position"));
        map.moveCamera(CameraUpdateFactory.newLatLng(location));
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

}

Xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MapActivity">

    <TextView
        android:id="@+id/idLocationText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Location: "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <com.google.android.gms.maps.MapView
        android:id="@+id/idLocationMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        map:liteMode="true"
        map:mapType="none" />
</LinearLayout>