Convert between LatLng and Location

This example demonstrate how to convert between LatLng and Location. Refer onMapClick() in the code.

Convert between LatLng and Location


package com.example.androidmapsv2;

import java.util.Date;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.widget.TextView;

public class MainActivity extends Activity
implements OnMapClickListener{

private GoogleMap myMap;

TextView info;

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

FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment =
(MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();

myMap.setOnMapClickListener(this);

info = (TextView)findViewById(R.id.info);

myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
}



@Override
public void onMapClick(LatLng point) {
//myMap.addMarker(new MarkerOptions().position(point).title(point.toString()));

//The code below demonstrate how to convert between LatLng and Location

//Convert LatLng to Location
Location location = new Location("Test");
location.setLatitude(point.latitude);
location.setLongitude(point.longitude);
location.setTime(new Date().getTime()); //Set time as current Date
info.setText(location.toString());

//Convert Location to LatLng
LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());

MarkerOptions markerOptions = new MarkerOptions()
.position(newLatLng)
.title(newLatLng.toString());

myMap.addMarker(markerOptions);

}

}


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

<TextView
android:id="@+id/info"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

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

</LinearLayout>


The series:
A simple example using Google Maps Android API v2, step by step.

thumbnail
Title: Convert between LatLng and Location
Rating: 100% based on 99998 ratings. 10 user reviews.
Post by

Related articles :

0 comments:

Post a Comment

My Blog List

 
Copyright © 2015. About - Web Version - Mobile Version Sitemap - Contact - Privacy