To get MyLocation programmatically, you have to enable my-location layer by calling setMyLocationEnabled(true). Then call getMyLocation(), it returns the currently displayed user location, or null if there is no location data available. Please noted that MyLocation may be need long time to available.
MainActivity.java
package com.example.androidmapex;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
import android.app.FragmentManager;
public class MainActivity extends Activity{
private GoogleMap myMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment1 =
(MapFragment)myFragmentManager.findFragmentById(R.id.map1);
myMap = myMapFragment1.getMap();
myMap.setMyLocationEnabled(true);
myMap.setOnMapLongClickListener(myOnMapLongClickListener);
}
OnMapLongClickListener myOnMapLongClickListener =
new OnMapLongClickListener(){
@Override
public void onMapLongClick(LatLng point) {
myMap.addMarker(new MarkerOptions()
.position(point)
.title(point.toString()));
Location myLocation = myMap.getMyLocation();
if(myLocation == null){
Toast.makeText(getApplicationContext(),
"My location not available",
Toast.LENGTH_LONG).show();
}else{
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.add(point);
polylineOptions.add(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
myMap.addPolyline(polylineOptions);
}
}
};
}
layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<fragment
android:id="@+id/map1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5px"
class="com.google.android.gms.maps.MapFragment"/>
</LinearLayout>
Download the files.
The series:
A simple example using Google Maps Android API v2, step by step.
No comments:
Post a Comment