【问题标题】:How to place custom label under city names in Google Maps Android API v2如何在 Google Maps Android API v2 中的城市名称下放置自定义标签
【发布时间】:2023-01-05 21:16:02
【问题描述】:

我正在使用 Google Maps API v2 在 android 中显示地图。

是否可以在每个城市名称下放置温度标签,如下图所示。

【问题讨论】:

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


    【解决方案1】:

    无法获取城市名称的精确屏幕坐标,因此无法在每个城市名称下准确放置温度标签。但是您可以从地图中隐藏所有城市/城镇名称(和其他标签)

    (请查看Add a Styled Map了解更多详情)并从thisthat等数据库中获取城市坐标和名称,并根据需要显示城市名称和附加文本。

    要创建没有城市名称的地图,您可以使用Styled map wizard交互模式(将标签搜索栏移到左侧)

    然后单击“完成”按钮并像这样复制粘贴 JSON:

    [
      {
        "elementType": "labels",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      },
      {
        "featureType": "administrative.land_parcel",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      },
      {
        "featureType": "administrative.neighborhood",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      }
    ]
    

    放入项目的文件中,例如srcmain es aw o_city_names_map_style.json。然后您可以通过以下方式将此样式应用到您的地图:

    mGoogleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(getApplicationContext(), R.raw.no_city_names_map_style));

    对于放置文本,您可以使用 Markers 和自定义动态创建的仅包含文本的图标,例如就像thisuser2808624的回答一样:

    public BitmapDescriptor createPureTextIcon(String text) {
    
        Paint textPaint = new Paint(); // Adapt to your needs
    
        float textWidth = textPaint.measureText(text);
        float textHeight = textPaint.getTextSize();
        int width = (int) (textWidth);
        int height = (int) (textHeight);
    
        Bitmap image = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(image);
    
        canvas.translate(0, height);
    
        // For development only:
        // Set a background in order to see the
        // full size and positioning of the bitmap.
        // Remove that for a fully transparent icon.
        canvas.drawColor(Color.LTGRAY);
    
        canvas.drawText(text, 0, 0, textPaint);
        BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(image);
        return icon;
    }
    

    然后你可以用这种方式在地图上放置带有自定义文本的标记:

    mMap.addMarker(new MarkerOptions()
        .position(<city_location>)
        .icon(BitmapDescriptorFactory.fromBitmap(createPureTextIcon("Name Temperature")))
        .anchor(0.5f, 1));
    

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2015-03-26
      相关资源
      最近更新 更多