2013-05-14 4 views
39

Я хочу показать карту в моей деятельности.Как использовать MapView в android с помощью google map V2?

В Google Map V1 мы используем -

<com.google.android.maps.MapView 
     android:id="@+id/mapview" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:apiKey="@string/api_map_key" 
     android:clickable="true" 
     android:enabled="true" /> 

и расширить свою деятельность, используя класс MapActivity.

В Versing 2 он использует фрагмент вместо mapview и должен расширять активность с помощью FragmentActivity вместо обычной Activity. экс-

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

Теперь Могу ли я использовать таким же образом, чтобы создать MapView вместо фрагмента с помощью версии 2.()

Можно ли использовать MapView используя V2?

+0

проверьте документ https://developers.google.com/maps/documentation/android/start.Нет, вы должны использовать фрагмент – Raghunandan

+0

@Raghunandan. [MapView in V2] (https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapView) тоже. Вам не нужно использовать фрагмент. Обратите внимание, что «MapView» (и API в целом) из v1 и v2 несовместимы. –

+0

@ MaciejGórski Я видел документы, вы можете опубликовать ссылку на пример google map api v2 с помощью mapview. – Raghunandan

ответ

16

Более полный образец от here и here.

Или вы можете проверить мой образец макета. p.s нет необходимости поместить ключ API в представление карты.

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:orientation="vertical" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

    <com.google.android.gms.maps.MapView 
      android:id="@+id/map_view" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_weight="2" 
      /> 

    <ListView android:id="@+id/nearby_lv" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:background="@color/white" 
       android:layout_weight="1" 
      /> 

</LinearLayout> 
+2

Вторая ссылка работает для меня. – xtr

+0

Все эти пособия полезны, но они предназначены для «eclipse» или более старой версии «android studio» – faisal1208

+0

Да, вещи меняются, в частности, инструменты. – Robert

128

да, вы можете использовать MapView в v2 ... для получения более подробной информации вы можете получить помощь от этого

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{ 

    MapView mapView; 
    GoogleMap map; 

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

     // Gets the MapView from the XML layout and creates it 
     mapView = (MapView) v.findViewById(R.id.mapview); 
     mapView.onCreate(savedInstanceState); 


     mapView.getMapAsync(this); 


     return v; 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     map = googleMap; 
     map.getUiSettings().setMyLocationButtonEnabled(false); 
     map.setMyLocationEnabled(true); 
     /* 
     //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call 
     try { 
      MapsInitializer.initialize(this.getActivity()); 
     } catch (GooglePlayServicesNotAvailableException e) { 
      e.printStackTrace(); 
     } 
     */ 

     // Updates the location and zoom of the MapView 
     /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10); 
     map.animateCamera(cameraUpdate);*/ 
     map.moveCamera(CameraUpdateFactory.newLatLng(43.1, -87.9)); 

    } 

    @Override 
    public void onResume() { 
     mapView.onResume(); 
     super.onResume(); 
    } 


    @Override 
    public void onPause() { 
     super.onPause(); 
     mapView.onPause(); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     mapView.onDestroy(); 
    } 

    @Override 
    public void onLowMemory() { 
     super.onLowMemory(); 
     mapView.onLowMemory(); 
    } 

} 

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example" 
    android:versionCode="1" 
    android:versionName="1.0" > 

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

    <uses-permission android:name="android.permission.INTERNET"/> 
    <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"/> 

    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true"/> 

    <permission 
     android:name="com.example.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature"/> 
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/> 

    <application 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 

     <meta-data 
      android:name="com.google.android.maps.v2.API_KEY" 
      android:value="your_key"/> 

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

    </application> 

</manifest> 

some_layout.xml

<LinearLayout 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" > 

    <com.google.android.gms.maps.MapView android:id="@+id/mapview" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 

</LinearLayout> 
+2

Работает как шарм –

+0

i Получил этот тип ошибки Объявить об этом в файле манифеста ckpatel

+0

Добавить mapView.onResume(), чтобы отобразить карту сразу – Stephane

-4

У меня есть очень простой способ, чтобы сделать его работы 100%

Шаг 1: Создайте базовое действие и удалите все лишние вещи, такие как fab и реализация snakbar, чтобы они были чистыми.

Шаг 1,5: Добавьте их в свой XML:

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

Шаг 2: Создайте приватную переменную на верхней части OnCreate:

private GoogleMap googleMap; 

Шаг 3: Добавить это в OnCreate:

if (googleMap == null) { 
     googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapNB)).getMap(); 
    } 

    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 



     LatLng coordinate = new LatLng(21.182782, 72.830115); 
     CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 11); 
     googleMap.moveCamera(CameraUpdateFactory.newLatLng(coordinate)); 
     googleMap.animateCamera(yourLocation); 



    googleMap.setMyLocationEnabled(true); 
    googleMap.getUiSettings().setZoomControlsEnabled(true); 



    googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { 
     @Override 
     public boolean onMarkerClick(Marker marker) { 


      somefunction(); 

      return false; 
     } 
    }); 

Не забудьте добавить свои ключи api.

+2

Вопрос в том, чтобы использовать MapView, а не фрагмент. –

+0

хорошо это можно использовать для того же –

Смежные вопросы