如何在Google Map API v2中的MapFragment上显示多个标记?

时间:2012-12-13 07:31:00

标签: android google-maps google-maps-markers google-maps-api-2 supportmapfragment

我在我的应用程序中使用Google Map API v2来显示地图。

我已按照所有步骤操作,以便在我的应用程序中启用Google Map。

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(); 

另外,我有一个lat / long值列表。我想在MapFragment上显示它们,如何在MapFragment 上显示多个标记?

我尝试使用MapViewItemizedOverlay,但它对我不起作用。我相信我已正确创建SHA1密钥以获取API密钥,因为如果这是错误的,我也无法使用MapFragment查看地图,但我可以看到,如果我不传递lat / log值。

6 个答案:

答案 0 :(得分:33)

我是这样做的,用不同颜色的标记在地图上显示汽车位置:

    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()即可

答案 1 :(得分:4)

要使用geoCoder将地址(即123 Testing Street Lodi ca)转换为LatLng时添加多个标记以进行映射,下面的示例代码将起作用。

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

答案 2 :(得分:2)

我不知道也许你修复了代码,现在没关系,但在onCreate()

if (getIntent().getExtras() != null) {
   final Bundle bundle = getIntent().getBundleExtra("LOCATION");
   mLatitude = bundle.getDouble("LATITUDE");
   mLatitude = bundle.getDouble("LONGITUDE");
}

第二个mLatitude我认为它必须是mLongitude,就像你在下一行中调用它一样。

对不起,如果我迟到了答案而没用。

答案 3 :(得分:0)

尝试使用此代码调用您网站根目录中的xml文件 -

添加标记的一种方法是加载位于根目录下的xml文件(参见下面的代码),其中包含标记html。

此处的代码设置地图空间和侧栏列以保存地图和标记的链接。请注意,带有id的div标签和用于html和map项的侧边栏td id。

您可以设置标记,但请注意需要使用必须正确标记的特殊字符;例如,&符号(&amp;)实际上应编码为“&amp;” +“amp”+“;” (没有引号)。这同样适用于大于和小于字符,依此类推。如果你有几个标记,这是一件苦差事,但一旦到位,它就很容易改变,因为它不需要在应用程序内部构建或编码任何程序集。在读取文件的脚本中,技术上使用CDATA标记应该不需要使用特殊字符表示,但对于Gmaps API v2,我仍然使用它们。对于我的示例,xml文件名是example3.xml。

您可以像这样格式化xml:

<Markers>
<marker lat="47.881389" lng="-122.242222"
html='&lt;div style="background-color:#FFFF88;font-family:Tahoma; font-size:12px;padding:6px;  border:solid 1px black;"&gt;&lt;b&gt;SiteLines Park &#38; Playground Products&lt;/b&gt; &lt;br&gt;626 128th Street SW&lt;br&gt;Suite 104-A&lt;br&gt;Everett&#8218;&#160;WA 98204&lt;br&gt;Phone&#58; &#40;425&#41; 355-5655&lt;br&gt;&lt;b&gt;Toll&#160;Free&#58;&#160;&#40;800&#41;&#160;541-0869&lt;/b&gt;&lt;br&gt;Fax&#58;&#160;&#40;425&#41;&#160;347-3056&lt;br&gt;Email&#58;&#160;&lt;a href="mailto:info@sitelines.com" target="blank"&gt;emailus&#64;sitelines.com&lt;/a&gt;&lt;br&gt;Web&#58;&#160;&lt;a href="http://www.sitelines.com" target="blank"&gt;www.sitelines.com&lt;/a&gt; &lt;/div&gt;'label="SiteLines Park &#38; 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&amp;v=2&amp;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

//]]&gt;

答案 4 :(得分:0)

first craete方法 setupDestationLocation

  this.camera.getPicture(options).then((imagePath) => {
      this.base64.encodeFile(imagePath).then((base64Image: string) => {
        console.log(base64Image);
      }, (err) => {
        console.log(err);
        this.base64Image=err;
      });
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
        this.filePath.resolveNativePath(imagePath)
          .then(filePath => {
            let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
            let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
            this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
          });
      }
      else {
        var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
        var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
        this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
      }
    }, (err) => {
      this.presentToast('Error while selecting image.');
    });

现在只需在方法内部调用方法( onMapReady

 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);

  }

答案 5 :(得分:0)

您可以尝试以下方法:

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;
}