【问题标题】:Finding my location on map在地图上查找我的位置
【发布时间】:2017-11-16 16:41:27
【问题描述】:

*********问题解决了*********

代码已编辑,完全可以使用,谢谢大家

当我在我的应用程序中按下一个按钮时,我想在谷歌地图上找到我自己的位置,所以我写了这段代码,但它没有在地图上找到我,它只是一张我见过的没有任何标记的地图其他人问这个,但我想我错过了一些东西!我真的需要帮助

它是我的

public class MainActivity extends AppCompatActivity {

private Button mbutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mbutton = (Button) findViewById(R.id.map);
    mbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MapsActivity.class);

                startActivity(intent);

        }
    });
}

}

还有我的地图

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{


private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps); 
    SupportMapFragment mapFragment = (SupportMapFragment)
                getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

}

private void setUpMapIfNeeded() {


            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    // TODO Auto-generated method stub
                    mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                }
            });

        }
    }

@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;

    try{
        mMap.setMyLocationEnabled(true);

        setUpMapIfNeeded();



    } catch(SecurityException e){

        Toast.makeText(getApplicationContext(),"App doesn't have the permission to gps... ",Toast.LENGTH_SHORT).show();
    }}}

这是我的清单文件

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

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.secu" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps"></activity>
</application>

</manifest>

【问题讨论】:

    标签: java android


    【解决方案1】:

    setUpMapIfNeeded() 方法替换为以下方法:

    private void setUpMapIfNeeded()
    {
        SupportMapFragment mapFragment = (SupportMapFragment)
                getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    
        if (mMap != null) // not sure this is usefull at this point
        {
            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener()
            {
                @Override
                public void onMyLocationChange(Location arg0)
                {
                    mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                }
            });
        }
    }     
    

    您将侦听器添加到 map == null 检查中,这将永远无法正常工作。

    【讨论】:

      【解决方案2】:

      试试这个:

      if (ContextCompat
              .checkSelfPermission(
                      getContext(),
                      android.Manifest.permission.ACCESS_FINE_LOCATION)
                      == PackageManager.PERMISSION_GRANTED
                      &&
                      ContextCompat.checkSelfPermission(
                         getContext(),
                         android.Manifest.permission.ACCESS_COARSE_LOCATION)
                      == PackageManager.PERMISSION_GRANTED) {
      
                  map.setMyLocationEnabled(true);
                  map.getUiSettings().setMyLocationButtonEnabled(true);
              }
      

      将这段代码放入setUpMapIfNeeded()

      if 条件检查位置权限是否可用。 我发布的代码中的重要部分是:

      map.setMyLocationEnabled(true);
      map.getUiSettings().setMyLocationButtonEnabled(true);
      

      JSharma 的答案使用融合位置提供程序,这是您使用的一个 api,如果您想更好地控制您的位置更新,它可以让您详细控制您希望接收位置更新的方式、频率等。

      如果你想要一个简单的位置更新,试试我的回答,看看是否有效,如果你需要更多的控制,你 JSharma 的

      【讨论】:

      • android studio 不让我使用一些功能,它无法解决...
      【解决方案3】:

      试试这个

      public class MainActivity extends AppCompatActivity implements 
        OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, 
        GoogleApiClient.OnConnectionFailedListener {
      
        SupportMapFragment mMap;
        LatLng CURRENT_LOCATION;
        GoogleApiClient mGoogleClient;
        GoogleMap mGoogleMap;
      
      
        @Override
        protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      
          int result=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
          if(result!=1)
          {
              Toast.makeText(this, "Availble", Toast.LENGTH_SHORT).show();
          }
          else {
              Toast.makeText(this, "Not Availble", Toast.LENGTH_SHORT).show();
          }
      
          mGoogleClient= new GoogleApiClient.Builder(this)
                  .addConnectionCallbacks(this)
                  .addOnConnectionFailedListener(this)
                  .addApi(LocationServices.API)
                  .build();
      
          mMap= (SupportMapFragment) 
      getSupportFragmentManager().findFragmentById(R.id.my_map);
          mMap.getMapAsync(this);
      }
      
      
      @Override
      protected void onStart() {
          super.onStart();
          mGoogleClient.connect();
      }
      
      @Override
      public void onMapReady(GoogleMap googleMap) {
      
          mGoogleMap=googleMap;
          googleMap.setMyLocationEnabled(true);
          googleMap.getUiSettings().setZoomControlsEnabled(true);
          googleMap.getUiSettings().setZoomGesturesEnabled(true);
      
      
      
      }
      
      @Override
      public void onConnected(Bundle bundle) {
      
          Location mCurrentLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
          if(mCurrentLocation!=null)
          {
      
              //here is your current location with lat & lon
      
              double lat=mCurrentLocation.getLatitude();
              double lon=mCurrentLocation.getLongitude();
      
              Log.e(">>>",String.valueOf(lat));
              Log.e(">>>",String.valueOf(lon));
      
      
              MarkerOptions marker=new MarkerOptions();
              marker.position(mCurrentLocation);
              marker.title("Android");
              marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
              mGoogleMap.addMarker(marker);
      
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mohali,8));
      
          }
          else {
              Toast.makeText(this, "Empty Location", Toast.LENGTH_SHORT).show();
          }
      }
      
      @Override
      public void onConnectionSuspended(int i) {
      
      }
      @Override
      public void onConnectionFailed(ConnectionResult connectionResult) {
      
      }
      

      }

       <?xml version="1.0" encoding="utf-8"?>
         <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.sts.mapdemoandroid">
        <uses-permission android:name="android.permission.INTERNET">
       </usespermission>
       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
       </uses-permission>
       <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
       </uses-permission>
      
      <application
          android:allowBackup="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:supportsRtl="true"
          android:theme="@style/AppTheme">
          <activity android:name=".MainActivity">
              <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.geo.API_KEY"
              android:value="AIzaSyBk4QJpLT8JoYfTpPMkxgDDFXJQGcmnHCg">
          </meta-data>
      
      </application>
      

      【讨论】:

        猜你喜欢
        • 2012-02-27
        • 2013-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多