android 获取地图,java – 在Android中获取地图地址或位置地址

我正在编写一个需要获取当前地图位置的应用程序.我的Map文件可以正常工作,但我需要从另一个Activity获取地址(请参阅下面的addressString).我尝试了getAddress / setAddress(setters / getters).它们不起作用.他们总是返回’无地址'(默认).

这是我的代码……

我怎样才能使它成为一个独立的Java类?或者从其他活动获取地址?

非常感谢.

此代码单独工作.

import android.content.Context;

import android.location.Address;

import android.location.Criteria;

import android.location.Geocoder;

import android.location.Location;

import android.location.LocationListener;

import android.location.LocationManager;

import android.os.Bundle;

import android.widget.TextView;

import java.io.IOException;

import java.util.List;

import java.util.Locale;

public class GetMapAddress extends MapActivity {

MapController mapController;

MyPositionOverlay positionOverlay;

MapController mc;

GeoPoint p;

String addressString = "No address found";

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.map);

MapView myMapView = (MapView) findViewById(R.id.myMapView);

mapController = myMapView.getController();

// Configure the map display options

myMapView.setSatellite(true);

myMapView.setStreetView(true);

// Zoom in

mapController.setZoom(17);

myMapView.setBuiltInZoomControls(true);

// Add the MyPositionOverlay

positionOverlay = new MyPositionOverlay();

List overlays = myMapView.getOverlays();

overlays.add(positionOverlay);

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_FINE);

criteria.setAltitudeRequired(false);

criteria.setBearingRequired(false);

criteria.setCostAllowed(true);

criteria.setPowerRequirement(Criteria.POWER_LOW);

String provider = locationManager.getBestProvider(criteria, true);

Location location = locationManager.getLastKnownLocation(provider);

updateWithNewLocation(location);

locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);

mc = myMapView.getController();

String coordinates[] = {

"1.352566007", "103.78921587"

};

double lat = Double.parseDouble(coordinates[0]);

double lng = Double.parseDouble(coordinates[1]);

p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

mc.animateTo(p);

mc.setZoom(17);

myMapView.invalidate();

}

private final LocationListener locationListener = new LocationListener() {

public void onLocationChanged(Location location) {

updateWithNewLocation(location);

}

public void onProviderDisabled(String provider) {

updateWithNewLocation(null);

}

public void onProviderEnabled(String provider) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}

};

/** Update the map with a new location */

private void updateWithNewLocation(Location location) {

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

String latLongString;

if (location != null) {

// Update my location marker

positionOverlay.setLocation(location);

// Update the map location.

Double geoLat = location.getLatitude() * 1E6;

Double geoLng = location.getLongitude() * 1E6;

GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());

mapController.animateTo(point);

double lat = location.getLatitude();

double lng = location.getLongitude();

latLongString = "Lat:" + lat + "\nLong:" + lng;

Geocoder gc = new Geocoder(this, Locale.getDefault());

try {

List

addresses = gc.getFromLocation(lat, lng, 1);

StringBuilder sb = new StringBuilder();

if (addresses.size() > 0) {

Address address = addresses.get(0);

for (int i = 0; i < address.getMaxAddressLineIndex(); i++)

sb.append(address.getAddressLine(i)).append("\n");

sb.append(address.getCountryName());

}

addressString = sb.toString();

} catch (IOException e) {

}

} else {

// Place the CellID here

latLongString = "No location found";

}

// This commented out line will include latitute and longtitute

// myLocationText.setText("Your Phone is Currently at.. \n" + latLongString + "\n" +

// addressString);

myLocationText.setText("Your Phone is Currently at.. \n" + addressString);

setAddress(addressString);

;

}

public void setAddress(String add) {

this.addressString = add;

}

public String getAddress() {

return addressString;

}

@Override

protected boolean isRouteDisplayed() {

return false;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
要实现地理编码,需要先解析OSM PBF文件并将其转换为可供查询的地图数据。以下是使用Java解析OSM PBF文件的代码示例: ```java import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import crosby.binary.osmosis.OsmosisReader; import crosby.binary.osmosis.OsmosisSerializer; import crosby.binary.file.BlockOutputStream; import org.openstreetmap.osmosis.core.container.v0_6.NodeContainer; import org.openstreetmap.osmosis.core.container.v0_6.WayContainer; import org.openstreetmap.osmosis.core.domain.v0_6.Node; import org.openstreetmap.osmosis.core.domain.v0_6.Way; import org.openstreetmap.osmosis.core.domain.v0_6.Tag; import org.openstreetmap.osmosis.core.task.v0_6.Sink; public class OsmParser { private Map<Long, Node> nodes; private List<Way> ways; public void parse(String filename) throws IOException { nodes = new HashMap<Long, Node>(); ways = new ArrayList<Way>(); OsmosisReader reader = new OsmosisReader(new FileInputStream(filename)); reader.setSink(new OsmosisSink()); reader.run(); } private class OsmosisSink implements Sink { public void process(NodeContainer nodeContainer) { Node node = nodeContainer.getEntity(); nodes.put(node.getId(), node); } public void process(WayContainer wayContainer) { Way way = wayContainer.getEntity(); ways.add(way); } public void complete() {} public void release() {} } // Example usage public static void main(String[] args) throws IOException { OsmParser parser = new OsmParser(); parser.parse("map.osm.pbf"); } } ``` 上面的代码将OSM PBF文件解析为一组节点和道路。节点表示地图上的点,道路表示连接节点的路径。这个示例只是一个简单的解析器,可能需要根据实际情况进行修改。 一旦您有了地图数据,您可以使用GeoTools或其他GIS库来进行地理编码。一个简单的示例是使用GeoTools的Geocoder类: ```java import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.referencing.CRS; import org.geotools.referencing.GeodeticCalculator; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Point; public class Geocoder { private SimpleFeatureSource featureSource; private MathTransform transform; private GeodeticCalculator calculator; public Geocoder(String shapefile) throws IOException, FactoryException { // Load shapefile into data store Map<String, Object> params = new HashMap<String, Object>(); params.put("url", new File(shapefile).toURI().toURL()); DataStore store = DataStoreFinder.getDataStore(params); // Get feature source String typeName = store.getTypeNames()[0]; featureSource = store.getFeatureSource(typeName); // Get coordinate reference system CoordinateReferenceSystem sourceCRS = featureSource.getSchema().getCoordinateReferenceSystem(); CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326"); // Create transform and calculator transform = CRS.findMathTransform(sourceCRS, targetCRS); calculator = new GeodeticCalculator(sourceCRS); } public String geocode(double latitude, double longitude) throws IOException { // Create point and transform to feature source CRS GeometryFactory factory = JTSFactoryFinder.getGeometryFactory(); Coordinate coord = new Coordinate(longitude, latitude); Point point = factory.createPoint(coord); Geometry transformed = JTS.transform(point, transform); // Create search filter SimpleFeatureType schema = featureSource.getSchema(); FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); Filter filter = ff.intersects(ff.property(schema.getGeometryDescriptor().getName()), ff.literal(transformed)); // Query feature source FeatureCollection features = featureSource.getFeatures(filter); FeatureIterator iterator = features.features(); try { if (iterator.hasNext()) { SimpleFeature feature = iterator.next(); return feature.getAttribute("NAME").toString(); } else { return null; } } finally { iterator.close(); } } // Example usage public static void main(String[] args) throws Exception { Geocoder geocoder = new Geocoder("map.shp"); String address = geocoder.geocode(37.7749, -122.4194); System.out.println(address); } } ``` 上面的代码使用GeoTools加载一个形状文件作为参考数据,并提供一个`geocode`方法来查找给定坐标的地址。该方法使用`GeodeticCalculator`计算两个点之间的距离,并使用`Filter`过滤器查询特定的地理位置

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值