我使用Google Map API v2
在我的应用程序,以显示地图。
我按照所有的步骤,即要遵循,使谷歌地图在我的应用程序。
public class PinLocationOnMapView extends FragmentActivity {
private double mLatitude = 0.0, mLongitude = 0.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SupportMapFragment fragment = SupportMapFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, fragment).commit();
}
}
如果我用这个代码,它让我看到地图,但如果我提供我的纬度/经度值,地图图块不加载,我只看到白色的瓷砖。
以下是写在上面类的onCreate()的代码:
if (getIntent().getExtras() != null) {
final Bundle bundle = getIntent().getBundleExtra("LOCATION");
mLatitude = bundle.getDouble("LATITUDE");
mLongitude = bundle.getDouble("LONGITUDE");
} else {
finish();
}
GoogleMapOptions options = new GoogleMapOptions();
LatLng latLng = new LatLng(mLatitude, mLongitude);
CameraPosition cameraPosition;// = new CameraPosition(latLng, 0, 0, 0);
cameraPosition = CameraPosition.fromLatLngZoom(latLng, (float) 14.0);
options.mapType(GoogleMap.MAP_TYPE_SATELLITE).camera(cameraPosition)
.zoomControlsEnabled(true).zoomGesturesEnabled(true);
SupportMapFragment fragment = SupportMapFragment.newInstance(options);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, fragment).commit();
另外,我有纬度/长值的列表。 我想告诉他们MapFragment
, 如何显示在多个标记MapFragment
?
我试着用MapView
与ItemizedOverlay
,但它并没有为我工作。 我相信我已经正确地创建了SHA1
键获得API
密钥,因为如果错了,我不能用看地图MapFragment
为好,但我可以看到,如果我没有通过纬度/经度值。
Answer 1:
我不喜欢这样,以显示与不同颜色的标记在地图上车的位置:
private void addMarkersToMap() {
mMap.clear();
for (int i = 0; i < Cars.size(); i++) {
LatLng ll = new LatLng(Cars.get(i).getPos().getLat(), Cars.get(i).getPos().getLon());
BitmapDescriptor bitmapMarker;
switch (Cars.get(i).getState()) {
case 0:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
Log.i(TAG, "RED");
break;
case 1:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
Log.i(TAG, "GREEN");
break;
case 2:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE);
Log.i(TAG, "ORANGE");
break;
default:
bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
Log.i(TAG, "DEFAULT");
break;
}
mMarkers.add(mMap.addMarker(new MarkerOptions().position(ll).title(Cars.get(i).getName())
.snippet(getStateString(Cars.get(i).getState())).icon(bitmapMarker)));
Log.i(TAG,"Car number "+i+" was added " +mMarkers.get(mMarkers.size()-1).getId());
}
}
}
汽车是一个ArrayList
自定义对象和mMarkers的是一个ArrayList
标记。
注意:您可以在这样的片段显示地图:
private GoogleMap mMap;
....
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Hide the zoom controls as the button panel will cover it.
mMap.getUiSettings().setZoomControlsEnabled(false);
// Add lots of markers to the map.
addMarkersToMap();
// Setting an info window adapter allows us to change the both the
// contents and look of the
// info window.
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
// Set listeners for marker events. See the bottom of this class for
// their behavior.
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnMarkerDragListener(this);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressLint("NewApi")
// We check which build version we are using.
@Override
public void onGlobalLayout() {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < mAvailableCars.size(); i++) {
LatLng ll = new LatLng(Cars.get(i).getPos().getLat(), Cars.get(i).getPos().getLon());
bld.include(ll);
}
LatLngBounds bounds = bld.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 70));
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
}
}
并调用setUpMapIfNeeded()
中onCreate()
Answer 2:
要添加多个标记,而使用地理编码器将地址(即123测试街洛迪CA),以经纬度来图,下面的实例代码将工作。
// convert address to lng lat and add markers to map
public void addMarkersToMap() {
mMap.clear();
Double[] latitude = new Double[addressArrayList.size()];
Double[] longitude = new Double[addressArrayList.size()];
String[] addrs = new String[addressArrayList.size()];
addrs = addressArrayList.toArray(addrs);
List<Address> addressList;
if (addrs != null && addrs.length > 0) {
for (int i = 0; i < addrs.length; i++) {
try {
addressList = geoCoder.getFromLocationName(addrs[i], 1);
if (addressList == null || addressList.isEmpty() || addressList.equals("")) {
addressList = geoCoder.getFromLocationName("san francisco", 1);
}
latitude[i] = addressList.get(0).getLatitude();
longitude[i] = addressList.get(0).getLongitude();
System.out.println("latitude = " + latitude[i] + " longitude = " + longitude[i]);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude[i], longitude[i]))
.title(namesArrayList.get(i))
.snippet(addressArrayList.get(i))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.alpha(0.7f)
);
} catch (Exception e) {
e.printStackTrace();
} // end catch
}
}
} //end addMarkersToMap
Answer 3:
我不知道也许ü固定的代码,现在是好的,但在onCreate()
if (getIntent().getExtras() != null) {
final Bundle bundle = getIntent().getBundleExtra("LOCATION");
mLatitude = bundle.getDouble("LATITUDE");
mLatitude = bundle.getDouble("LONGITUDE");
}
第二mLatitude
我认为这是mLongitude
只是像你把它在未来的行。
很抱歉,如果我的答复晚,也是没用的。
Answer 4:
试试这个代码在您的网站的根目录调用的XML文件 -
以添加标记物的一种方式是通过加载驻留在根目录下的XML文件(见下面的代码),其中包含标记的HTML。
代码在这里设置了地图空间和侧栏列,以保存地图和链接标记。 需要注意的是都与一个id以及用于在HTML和地图项的侧边栏TD ID的div标签。
您可以设置标记,但要注意需要使用,必须正确标记的特殊字符; 例如号(&)实际上应编码为“&” +“AMP” +“;” (不带引号)。 这同样适用于大于和小于字符,等等。 这是,如果你有几个标志是件苦差事,但一旦发生很容易改变,因为它不需要任何组件需要待建或在应用程序中的编码。 在读取文件时,使用CDATA标签技术上应使用特殊字符表示的是不必要的,但对于Gmaps API第2版,我反正使用它们的脚本。 在我的例子XML文件名是example3.xml。
您可以格式化像这样的XML:
<Markers>
<marker lat="47.881389" lng="-122.242222"
html='<div style="background-color:#FFFF88;font-family:Tahoma; font-size:12px;padding:6px; border:solid 1px black;"><b>SiteLines Park & Playground Products</b> <br>626 128th Street SW<br>Suite 104-A<br>Everett‚ WA 98204<br>Phone: (425) 355-5655<br><b>Toll Free: (800) 541-0869</b><br>Fax: (425) 347-3056<br>Email: <a href="mailto:info@sitelines.com" target="blank">emailus@sitelines.com</a><br>Web: <a href="http://www.sitelines.com" target="blank">www.sitelines.com</a> </div>'label="SiteLines Park & Playground Products" />
</Markers>
And for the html and script:
<form style="background-color: #ffffff;" id="form1" runat="server">
<div style="text-align: center;">
<table style="border: 1px currentColor; vertical-align: middle;">
<tbody>
<tr>
<td style="background-color: #bbcae3; vertical-align: top;">
<div style="background-color: #e4e4e4; font-family: Tahoma; font-size: 12px; line-height: 22px; padding: 5px; text-decoration: underline; width: 210px; color: #000000; text-align: left;" id="side_bar"></div>
</td>
<td>
<div style="height: 600px; width: 600px;" id="map"></div>
</td>
</tr>
</tbody>
</table>
</div>
</form>
<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAyUoL7QQqyBn6qU653XJGLxSjEdRKL8ahnZ9z8zIKzjlyzNOP2RRCsKP_vlAEzWT8jzEKS0_9RrXOAg"></script>
<script type="text/javascript">// <![CDATA[
if (GBrowserIsCompatible()) {
// this variable will collect the html which will eventualy be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];
var i = 0;
// A function to create the marker and set up the event window
function createMarker(point, name, html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
gmarkers[i] = marker;
htmls[i] = html;
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
i++;
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
gmarkers[i].openInfoWindowHtml(htmls[i]);
}
// create the map
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(0, 0), 0);
//
// ===== Start with an empty GLatLngBounds object =====
var bounds = new GLatLngBounds();
// Read the data from example3.xml
GDownloadUrl("/testStore/example3.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat, lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point, label, html);
map.addOverlay(marker);
}
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/
// http://econym.googlepages.com/index.htm
//]]>
Answer 5:
第一个方法了解创建setupDestationLocation
public void setupDestationLocation(double longlat, double latitue, String title) {
LatLng Shop = new LatLng(longlat, latitue);
/* if (DestinationMarker != null) {
DestinationMarker.remove();
}*/
DestinationMarker = mMap.addMarker(new MarkerOptions()
.position(Shop)
.title(market_n)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker_shop)));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(Shop, 14);
mMap.animateCamera(cameraUpdate);
}
现在,在方法只需调用内部方法(onMapReady)
String title = "market";
for(int i = 0 ; i < 8 ; i++ ) {
double offset = i / 08d;
setupDestationLocation(longlat+offset,latitue,title+i);
}
Answer 6:
你可以试试这个:
public double getDistanceinKm(double lat1, double long1, double lat2, double long2) {
Location startPoint = new Location("locationA");
startPoint.setLatitude(lat1);
startPoint.setLongitude(long1);
Location endPoint = new Location("locationA");
endPoint.setLatitude(lat2);
endPoint.setLongitude(long2);
double distanceInKiloMeters = startPoint.distanceTo(endPoint) / 1000;
return distanceInKiloMeters;
}
文章来源: How to show multiple markers on MapFragment in Google Map API v2?