如何创建从给定的坐标列表中显示附近位置的Android应用程序 [英] How Do I Create An Android Application That Displays Nearby Places From A Given List Of Coordinates
问题描述
请问如何创建一个Android应用程序,检查并比较用户当前位置的纬度和经度列表,并在可点击的列表视图中显示其纬度和经度最接近用户当前位置的位置。我已经能够访问我在地图上的位置并映射出来,也可以映射出从我的位置到给定坐标的路线,但我不知道如何包含坐标列表并将它们与我的位置进行比较以便让它只显示附近的位置。下面是我的java文件和xml文件。谢谢
MYGIRNE.java
please How do i create an android application that checks and compare a list of latitude and longitude to the user's current location and displays places whose latitude and longitude are closest to the user's current location in a clickable listview. i have been able to access my location on the map and map out and also to map out a route from my location to a given coordinate but i don't know how to include a list of coordinates and compare them to my location so as to get it to display only the locations that are nearby. below is my java file and xml file. thank you
MYGIRNE.java
package com.firsttry.cyptour;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class MYGIRNE extends FragmentActivity {
GoogleMap map;
ArrayList<latlng> markerPoints;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygirne);
// Initializing
markerPoints = new ArrayList<latlng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
if(map!=null){
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// change map type to hybrid
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// set traffic
map.setTrafficEnabled(true);
// get user location
// Setting onclick event listener for the map
LocationManager manager=(LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
String provider =manager.getBestProvider(criteria, true);
Location cloc=manager.getLastKnownLocation(provider);
double lat=35.177;
double lng =33.3456;
lat =cloc.getLatitude();
lng= cloc.getLongitude();
LatLng latlng = new LatLng (lat,lng);
map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
map.addMarker(new MarkerOptions()
.title("Your Current Location")
.position(latlng));
LatLng GIRNE =
new LatLng(35.323710400000000000,33.314941299999990000);
map.addMarker(new MarkerOptions()
.position(GIRNE)
.title("GIRNE")
.snippet("GIRNE CITY CENTRE")
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_AZURE)));
// Getting URL to the Google Directions API
String url = getDirectionsUrl(latlng, GIRNE);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
private String getDirectionsUrl(LatLng latlng,LatLng GIRNE){
// Origin of route
String str_origin = "origin="+latlng.latitude+","+latlng.longitude;
// Destination of route
String str_dest = "destination="+GIRNE.latitude+","+GIRNE.longitude;
// Sensor enabled
String sensor = "sensor=true";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<string,>{
// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<string,>>> >{
// Parsing the data in non-ui thread
@Override
protected List<list><hashmap><string,>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<list><hashmap><string,>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
Directions parser = new Directions();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<list><hashmap><string,>>> result) {
ArrayList<latlng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){>
points = new ArrayList<latlng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<hashmap><string,>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){>
HashMap<string,string> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.CYAN);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mygirne, menu);
return true;
}
}
mygirne.xml
mygirne.xml
<relativelayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.firsttry.cyptour.MYGIRNE" >
<fragment>
android:id="@+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="com.google.android.gms.maps.SupportMapFragment" />
</fragment></relativelayout>
AndroidManifest.xml
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
package="com.firsttry.cyptour"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk>
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- External storage for caching. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- My Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature>
android:glEsVersion="0x00020000"
android:required="true" />
<permission>
android:name="com.firsttry.cyptour.permission.MAPS_RECEIVE"
android:protectionLevel="signature" >
</permission>
<application>
android:allowBackup="true"
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="AIzaSyDgRSTCYVtoc3vLqRR-XX0_RkyoofblyXc" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity>
android:name=".MYGIRNE"
android:label="@string/title_activity_mygirne" >
</activity>
</application>
推荐答案
这不是CP通常的工作方式。这里最重要的目标是学习和帮助学习。
你应该自己尝试,当你遇到困难时来到这里,对你的代码,设计等有一个具体的问题。
请查看你有什么尝试? [ ^ ]至看看我的意思是一个很好的解释。
不要忘记这里的人不会得到报酬。此外,如果我们给你一个随时可用的解决方案,它不会帮助你,因为你不会从中学到任何东西。
As一般方法:
步骤1)做一点研究。谷歌是一个很好的起点
ie。开始的地方:
http://developer.android.com/index.html [ ^ ]
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html [ ^ ]
http://www.youtube.com/watch?v=7-n6p6RxSS8 [ ^ ]
步骤2)开始编码
步骤3)编译并使用调试来解决小问题
步骤4)当你遇到问题时你不知道如何解决但至少你试过它,然后回来问一些具体的代码片段给出了问题
很抱歉,如果这不是你想要的答案。但你的问题有点太宽,无法在快速答案中得到解答。如果你对具体问题提出10个具体问题,那么你会得到更好的帮助,而不是关于如何引导的大问题
This is not how CP usually works. Most important goal here is to learn and help learning.
You are supposed to try it on your own, and come here when you got stuck with something, with a concrete question about your code, design, etc.
Please have a look to What have you tried?[^] to see a good explanation about what I mean.
Don't forget people here don't get payed. And besides, if we give you a ready-to-go solution, it is not going to help you because you are not going to learn anything from it.
As a general approach:
Step 1) Do a little research. Google is a good start point
ie. Places to start:
http://developer.android.com/index.html[^]
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html[^]
http://www.youtube.com/watch?v=7-n6p6RxSS8[^]
Step 2) Start coding
Step 3) Compile and use the debug to solve little issues
Step 4) When you get a problem you don't know how to solve but at least you tried it, then come back and ask for something concrete with a snippet of the code giving problems
Sorry if this is not the answer you were looking for. But your question is a bit too wide to be answered at the "Quick" Answers. It is better and you get faster help if you make 10 concrete questions about concrete problems, than a big question about a "how-to guide"
开始研究创建和监控地理围栏 [ ^ ]。
这篇关于如何创建从给定的坐标列表中显示附近位置的Android应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!