我试图在 Android 中显示两个 MarkerOptions 点之间的行车路线。我找到了 this tutorial here ,这对我来说效果很好,但我正在尝试对其进行调整,以便 MarkerOptions 是我当前的位置和一个固定的 LatLng 对象,而不是当您获得两点时触摸 map 。所以我得到了我当前的位置,LatLng = updatedLatLng,固定位置是 LatLng = wcbcLatLng。在本教程中,onMapClick 方法如下所示:
public void onTouchMap(){
// Setting onclick event listener for the map
this.mapG3.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Already two locations
if (Geo4.this.markerPoints.size() > 1) {
Geo4.this.markerPoints.clear();
Geo4.this.mapG3.clear();
}
// Adding new item to the ArrayList
Geo4.this.markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and for
* the end location, the color of marker is RED.
*/
if (Geo4.this.markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker
(BitmapDescriptorFactory.HUE_GREEN));
} else if (Geo4.this.markerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory
.defaultMarker
(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
Geo4.this.mapG3.addMarker(options);
// Checks, whether start and end locations are captured
if (Geo4.this.markerPoints.size() >= 2) {
LatLng origin = Geo4.this.markerPoints.get(0);
LatLng dest = Geo4.this.markerPoints.get(1);
// Getting URL to the Google Directions API
String url = Geo4.this.getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}//-- END Method
这是我要修改的方法,以便它查找我的 updatedLatLng & wcbcLatLng 而不是 LatLng origin & LatLng dest 该方法当前正在使用。任何帮助,将不胜感激!这是我的完整 Activity :
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.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
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 android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
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.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
public class Geo4 extends FragmentActivity implements LocationListener {
GoogleMap mapG3;
ArrayList<LatLng> markerPoints;
TextView mapInfo_TV;
LocationManager locMan;
SupportMapFragment sMf;
Button back_btn, zoom_btn;
MarkerOptions startMO, wcbcMO, broncoMO;
MarkerOptions markers;
Marker currentMarker, wcbcMarker, broncoMarker;
LatLng updatedLatLng, directionsLatLng;
LatLng wcbcLatLng = new LatLng(30.393903, -97.682871);
LatLng oskiLatLng = new LatLng(30.474570, -97.973889);
LatLng point, point3t, point4t;
CameraUpdate cameraUpdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geo3);
back_btn = (Button) findViewById(R.id.backMap_g3_btn);
zoom_btn = (Button) findViewById(R.id.marker_g3_btn);
this.mapInfo_TV = (TextView) this.findViewById(R.id.map_g3Info_TV);
// Initializing
this.markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
sMf = (SupportMapFragment) this.getSupportFragmentManager()
.findFragmentById(R.id.map_g3_FRAG);
// Getting Map for the SupportMapFragment
this.mapG3 = sMf.getMap();
// --- fire Methods
googlePlay();
getCurrentLocation();
onTouchMap();
// --- END fire Methods
// --- Back button
back_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// mapG3.clear();
Intent backmapI = new Intent(
"com.my.package.BUTTON_INTERFACE");
startActivity(backmapI);
}
});
// --- end Back button
// --- Zoom button
zoom_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
getDirections4T(point4t);
}
});
// --- end Zoom button
}// --- END onCreate
// --- Methods ----
public void googlePlay() {
// ---- Google Play
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
//Toast.makeText(getApplicationContext(),"Services Launched Fo Sho'",Toast.LENGTH_SHORT).show();
}
}
// ---- END Method
public void getCurrentLocation(){
// Getting LocationManager object from System Service LOCATION_SERVICE
locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = locMan
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = locMan
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GPS settings
if (!enabledGPS && !enabledWiFi) {
Toast.makeText(getApplicationContext(), "GPS signal not found",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locMan.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location oLc = locMan.getLastKnownLocation(provider);
if (oLc != null) {
onLocationChanged(oLc);
}
locMan.requestLocationUpdates(provider, 20000, 0, this);
}//--- END Method
public void zoomToFit() {
// --- zoom to fit
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(wcbcLatLng);
builder.include(updatedLatLng);
LatLngBounds bounds = builder.build();
int padding = 50; // offset from edges of the map in pixels
cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mapG3.animateCamera(cameraUpdate);
// --- END zoom to fit
}// --- END Method
public void addwcbcMarkerOption() {
wcbcMO = new MarkerOptions().position(wcbcLatLng).title(
"Destination");
wcbcMO.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
mapG3.addMarker(wcbcMO);
cameraUpdate = CameraUpdateFactory.newLatLngZoom(wcbcLatLng, 15);
mapG3.animateCamera(cameraUpdate);
}// --- END Method
public void getDirections4T(LatLng point4t) {
Geo4.this.markerPoints.add(point4t);
markers = new MarkerOptions();
markers.position(wcbcLatLng);
markers.position(oskiLatLng);
if (Geo4.this.markerPoints.size() == 1) {
markers.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (Geo4.this.markerPoints.size() == 2) {
markers.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
Geo4.this.mapG3.addMarker(markers);
}//--- END Method
public void onTouchMap(){
// Setting onclick event listener for the map
this.mapG3.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Already two locations
if (Geo4.this.markerPoints.size() > 1) {
Geo4.this.markerPoints.clear();
Geo4.this.mapG3.clear();
}
// Adding new item to the ArrayList
Geo4.this.markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and for
* the end location, the color of marker is RED.
*/
if (Geo4.this.markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker
(BitmapDescriptorFactory.HUE_GREEN));
} else if (Geo4.this.markerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory
.defaultMarker
(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
Geo4.this.mapG3.addMarker(options);
// Checks, whether start and end locations are captured
if (Geo4.this.markerPoints.size() >= 2) {
LatLng origin = Geo4.this.markerPoints.get(0);
LatLng dest = Geo4.this.markerPoints.get(1);
// Getting URL to the Google Directions API
String url = Geo4.this.getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}//-- END Method
private String getDirectionsUrl(LatLng updatedLatLng, LatLng dest) {
// Origin of route
String str_updatedLatLng = "origin=" + updatedLatLng.latitude + ","
+ updatedLatLng.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_updatedLatLng + "&" + 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, Void, 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 = Geo4.this.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, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
@Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
Geo3JSON parser = new Geo3JSON();
// 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, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if (result.size() < 1) {
Toast.makeText(Geo4.this.getBaseContext(), "No Points",
Toast.LENGTH_SHORT).show();
return;
}
// 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, 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);
if (j == 0) { // Get distance from the list
distance = point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
duration = point.get("duration");
continue;
}
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(4);
lineOptions.color(Color.RED);
}
Geo4.this.mapInfo_TV.setText("Distance: " + distance + "les");
// Drawing polyline in the Google Map for the route
Geo4.this.mapG3.addPolyline(lineOptions);
}
}
// --- END Methods
// --- onLocationListener
@Override
public void onLocationChanged(Location oLc) {
updatedLatLng = new LatLng(oLc.getLatitude(), oLc.getLongitude());
startMO = new MarkerOptions().position(updatedLatLng)
.title("You Are Here")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mapG3.addMarker(startMO);
addwcbcMarkerOption();
locMan.removeUpdates(this);
}
@Override
public void onProviderDisabled(String provider) {
//
}
@Override
public void onProviderEnabled(String provider) {
//
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//
}
// --- END onLocationListener
@Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
finish();
}
// --- inflated menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.wcbcv, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil
.getOpenSourceSoftwareLicenseInfo(getApplicationContext
());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(
Geo4.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
// --- END inflated menu
}
最佳答案
我想通了。我的大部分 onTouchMap() 都在获取 onTouch 信息并将这些整数转换为 LatLng 值。因为我已经有了 LatLng 值,所以我只需要采用 LatLng 并从中获取 JSON 数据的方法的最后三行.所以我重写了方法以首先添加 MarkerOptions 和 LatLng 值,然后我添加了旧方法的最后 3 行。这就是我的新方法的样子,它可以正常工作(通过调用其他 3 个方法)并绘制折线并在 TextView 中显示以英里为单位的距离。
public void addMarkers(){
wcbcMO = new MarkerOptions().position(wcbcLatLng)
.title("Destination")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
mapG3.addMarker(wcbcMO);
startMO = new MarkerOptions().position(updatedLatLng)
.title("You Are Here")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mapG3.addMarker(startMO);
// Getting URL to the Google Directions API
String url = Geo4.this.getDirectionsUrl(updatedLatLng, wcbcLatLng);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}//--- END Method
关于android - 在 Android 上的 Google Maps API v2 中显示路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920187/
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问
我将我的Rails应用程序部署到OpenShift,它运行良好,但我无法在生产服务器上运行“Rails控制台”。它给了我这个错误。我该如何解决这个问题?我尝试更新rubygems,但它也给出了权限被拒绝的错误,我也无法做到。railsc错误:Warning:You'reusingRubygems1.8.24withSpring.UpgradetoatleastRubygems2.1.0andrun`gempristine--all`forbetterstartupperformance./opt/rh/ruby193/root/usr/share/rubygems/rubygems
我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article
我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
目前,Itembelongs_toCompany和has_manyItemVariants。我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不显示该表单。只有当我使用单数时才会显示。我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?提前致谢。注意:下面的代码片段中省略了不相关的代码。编辑:不知道这是否相关,但我正在使用CanCan进行身份验证。routes.rbresources:companiesdoresources:itemsenditem.rbclassItemi
如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]