Итак, я работаю над приложением для Android, и я написал код для карт Google, который некоторое время назад работал нормально. Но затем я подключил Firebase, который дал мне несколько ошибок, из-за которых мне пришлось обновить зависимости (раньше я использовал play-services-gcm: 12.0.1). Сейчас я работаю над следующими зависимостями:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.getdevicelocation"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    implementation 'com.google.firebase:firebase-appindexing:10.0.1'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation "com.google.android.gms:play-services-gcm:15.0.1"
    implementation 'com.google.firebase:firebase-core:16.0.0'

}

apply plugin: 'com.google.gms.google-services' 

Я получаю следующую ошибку.

error: package com.google.android.gms.maps does not exist

Я знаю, это означает, что пакет не найден в предоставленной мной библиотеке. Ниже приведен мой код для mapsactivity.xml.

package com.example.getdevicelocation;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

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.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        // Add a marker in Sydney and move the camera
        LatLng loc_1 = new LatLng(30.275285, 77.047580);
        mMap.addMarker(new MarkerOptions().position(loc_1).title("Open Dumping site unattended since 2 months").
                icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
        mMap.moveCamera(CameraUpdateFactory .newLatLngZoom(loc_1, 12));

    }
}

Есть ли другой способ доступа к картам Google в новых зависимостях? Что-то не так с моим кодом.

1
Arjun Kashyap 23 Окт 2018 в 11:43

2 ответа

Лучший ответ

ошибка: пакет com.google.android.gms.maps не существует

Вы должны добавить

implementation "com.google.android.gms:play-services-maps:15.0.0" //16.0.0

Тогда Clean-Rebuild-Run .

< Сильный > FYI

Вам следует обновить версию firebase-appindexing .

< Сильный > Пример

implementation 'com.google.firebase:firebase-appindexing:16.0.2'
1
IntelliJ Amiya 23 Окт 2018 в 09:04
for Google map there's no need to add firebase dependency.

here I am sharing you complete code for google map.

in manifest you need to add google map library-

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

        <activity android:name=".activities.ActivityMap" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    <!-- Allow to connect with internet -->
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

to use google maps you need to get map key.

Open your command prompt by typing cmd in your run. Start ⇒ Run ⇒ type cmd.

c:\<path-to-jdk-dir>\bin\keytool.exe -list -alias androiddebugkey 

-keystore "C:\users\<user-name>\.android\debug.keystore" -storepass android -keypass android


keytool.exe -list -alias androiddebugkey -keystore "C:\users\ravi\.android\debug.keystore" -storepass android -keypass android


Go to https://developers.google.com/maps/documentation/android-sdk/intro?csw=1

 and get your map key by giving MD5 fingerprint.

and generate your key-

layout - place your key to layout.

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="05M-7qOGbEjYduPPUdQgJt9ysL8HToawGdvu_ow"
/>


Extend your activity by MapActivity.


to get map - 

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

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

// to display zooming controls

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);


    }

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

mapView.setSatellite(true); // Satellite View
mapView.setStreetView(true); // Street View
mapView.setTraffic(true); // Traffic View

You can also change map type like satellite, streetview etc.,

///////////////////////////////////////////////////////

To show a location on the map by passing latitude and longitude of that location.

MapController mc = mapView.getController();
double lat = Double.parseDouble("48.85827758964043"); // latitude
double lon = Double.parseDouble("2.294543981552124"); // longitude
GeoPoint geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
mc.animateTo(geoPoint);
mc.setZoom(15);
mapView.invalidate(); 

/////////////////////////////////////////

For displaying marker on the map you need to create new class which extends ItemizedOverlay.
Create new class and name it as AddItemizedOverlay.java and write following code.

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();
       }

    }

/////////////////////////////////////////////////

    Add this code to your ActivityMap -

    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);

    ////////////////////////////////////////////////////////////////////////////

    You can also get the latitude and longitude of location which was touched. Open your AddItemizedOverlay.java and add below method.

    public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {

           /*................. Add this method ........*/
           @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;
           } 

        }

    now run your project.
2
s.j 23 Окт 2018 в 09:48
52944757