谷歌地图获取坐标中心(在多边形中央放置标签)

4

我使用谷歌地图,在地图上标出区域,就像这样:

enter image description here

 var areaCoords2 = [
        new google.maps.LatLng(32.819649, 35.073102),
        new google.maps.LatLng(32.819604, 35.073026),
        new google.maps.LatLng(32.817169, 35.071321),
        new google.maps.LatLng(32.817097, 35.071353),
        new google.maps.LatLng(32.816042, 35.073391),
        new google.maps.LatLng(32.818513, 35.075119),
        new google.maps.LatLng(32.818612, 35.075054)
    ];

我希望实现的目标是:将标签标记放置在标记红色区域的中心位置(大约)。

而不是使用静态的纬度和经度来放置它们(因为我有很多区域)。

有没有一种通过编程实现这样的方法呢?


另一个相关问题该问题的这个示例将标签放置在多边形的中心。 - geocodezip
另一种方法(适用于任何形状)是...https://dev59.com/Im855IYBdhLWcg3wilCD - Blablaenzo
5个回答

8
以下代码构建了一个 google.maps.Polygon,并在其边界中心放置了一个MapLabel。
        // Construct the polygon.
        var mypolygon2 = new google.maps.Polygon({
            paths: polyCoords,
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 3,
            fillColor: '#FF0000',
            fillOpacity: 0.35
        });

        mypolygon2.setMap(map);

        //Define position of label
        var bounds = new google.maps.LatLngBounds();
        for (var i=0; i< polyCoords.length; i++) {
          bounds.extend(polyCoords[i]);
        }

        var myLatlng = bounds.getCenter();

        var mapLabel2 = new MapLabel({
            text: '2',
            position: myLatlng,
            map: map,
            fontSize: 20,
            align: 'left'
        });
        mapLabel2.set('position', myLatlng);
        var obj = {};
        obj.poly = mypolygon2;
        obj.label = mapLabel2;

工作的代码片段

生成地图的截图

代码片段:

var map;
var gpolygons = [];
var infoWindow;

function initialize() {
  var mapOptions = {
    zoom: 17,
    center: new google.maps.LatLng(50.71392, -1.983551),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // Define the LatLng coordinates for the polygon.
  var triangleCoords = [
    new google.maps.LatLng(50.71433, -1.98392),
    new google.maps.LatLng(50.71393, -1.98239),
    new google.maps.LatLng(50.71388, -1.98226),
    new google.maps.LatLng(50.71377, -1.98246),
    new google.maps.LatLng(50.71332, -1.98296),
    new google.maps.LatLng(50.71334, -1.98324),
    new google.maps.LatLng(50.71374, -1.9845),
    new google.maps.LatLng(50.71436, -1.98389)
  ];

  // Construct the polygon.
  var mypolygon = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  mypolygon.setMap(map);

  //Define position of label
  var myLatlng = new google.maps.LatLng(50.71392, -1.983551);

  var mapLabel = new MapLabel({
    text: '1',
    position: myLatlng,
    map: map,
    fontSize: 20,
    align: 'left'
  });
  mapLabel.set('position', myLatlng);

  var obj = {};
  obj.poly = mypolygon;
  obj.label = mapLabel;
  gpolygons.push(obj);

  var polyCoords = [
    new google.maps.LatLng(50.713689004418, -1.9845771789550781),
    new google.maps.LatLng(50.71316590540595, -1.9829249382019043),
    new google.maps.LatLng(50.71296209901576, -1.983107328414917),
    new google.maps.LatLng(50.71296889257639, -1.9837510585784912),
    new google.maps.LatLng(50.713186285996215, -1.9845235347747803),
    new google.maps.LatLng(50.71293492476347, -1.9847595691680908),
    new google.maps.LatLng(50.71311155712187, -1.9853174686431885),
    new google.maps.LatLng(50.71335612390394, -1.9853603839874268),
    new google.maps.LatLng(50.713396884910225, -1.9850599765777588),
    new google.maps.LatLng(50.71348520030224, -1.9848453998565674),
    new google.maps.LatLng(50.71357351552787, -1.9846951961517334)
  ]

  // Construct the polygon.
  var mypolygon2 = new google.maps.Polygon({
    paths: polyCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  mypolygon2.setMap(map);

  //Define position of label
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < polyCoords.length; i++) {
    bounds.extend(polyCoords[i]);
  }

  var myLatlng = bounds.getCenter();

  var mapLabel2 = new MapLabel({
    text: '2',
    position: myLatlng,
    map: map,
    fontSize: 20,
    align: 'left'
  });
  mapLabel2.set('position', myLatlng);
  var obj = {};
  obj.poly = mypolygon2;
  obj.label = mapLabel2;
  gpolygons.push(obj);


  // Add a listener for the click event.  You can expand this to change the color of the polygon
  google.maps.event.addListener(mypolygon, 'click', showArrays);
  google.maps.event.addListener(mypolygon2, 'click', showArrays);


  infoWindow = new google.maps.InfoWindow();
}

/** @this {google.maps.Polygon} */
function showArrays(event) {

  //Change the color here
  // toggle it
  if (this.get("fillColor") != '#0000ff') {
    this.setOptions({
      fillColor: '#0000ff'
    });
  } else {
    this.setOptions({
      fillColor: '#ff0000'
    });
  }

  // Since this polygon has only one path, we can call getPath()
  // to return the MVCArray of LatLngs.
  var vertices = this.getPath();

  var contentString = '<b>My polygon</b><br>' +
    'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
    '<br>';

  // Iterate over the vertices.
  for (var i = 0; i < vertices.getLength(); i++) {
    var xy = vertices.getAt(i);
    contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' + xy.lng();
  }

  // Replace the info window's content and position.
  infoWindow.setContent(contentString);
  infoWindow.setPosition(event.latLng);

  infoWindow.open(map);
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.rawgit.com/googlemaps/js-map-label/gh-pages/src/maplabel.js"></script>
<title>Polygon Arrays</title>
<div id="map-canvas">
</div>


1

这里有一个针对Android/Java的方法,可以尝试进行调整以在Web上使用:

public Location GetCentrePointFromListOfLocations(List<Location> coordList)
{
    int total = coordList.size();

    double X = 0;
    double Y = 0;
    double Z = 0;

    for(Location location : coordList)
    {
        double lat = location.getLatitude() * Math.PI / 180;
        double lon = location.getLongitude() * Math.PI / 180;

        double x = Math.cos(lat) * Math.cos(lon);
        double y = Math.cos(lat) * Math.sin(lon);
        double z = Math.sin(lat);

        X += x;
        Y += y;
        Z += z;
    }

    X = X / total;
    Y = Y / total;
    Z = Z / total;

    double Lon = Math.atan2(Y, X);
    double Hyp = Math.sqrt(X * X + Y * Y);
    double Lat = Math.atan2(Z, Hyp);

    Location tempLocation = new Location("");
    tempLocation.setLatitude(Lat * 180 / Math.PI);
    tempLocation.setLongitude(Lon * 180 / Math.PI);

    return tempLocation;
}

它给出的是边界中心,而不是多边形中心。 - Zaid Mirza

0

这个对我来说可以使用动态多边形值。

截图
<script type="text/javascript" src="https://cdn.rawgit.com/googlemaps/js-map-label/gh-pages/src/maplabel.js"></script>

<script>

  // This example creates a simple polygon representing the Bermuda Triangle.
  var gpolygons = [];

  function initStaticMap() {
    var bounds = new google.maps.LatLngBounds();
    var latlng = new google.maps.LatLng(-22.5747697,-43.857650); //-22.820554842103107--43.184738187119365
    var map = new google.maps.Map(document.getElementById('map_canvas'), {
      zoom: 10,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
    });

    // Define the LatLng coordinates for the polygon's path.
    <?php if($store_delivery_zone){ foreach($store_delivery_zone as $point){ ?>
    var coord<?php echo $point['delivery_zone_id']; ?> = <?php echo $point['polygon_points']; ?>;

    // Construct the polygon.
    var poly<?php echo $point['delivery_zone_id']; ?> = new google.maps.Polygon({
      paths: coord<?php echo $point['delivery_zone_id']; ?>,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    poly<?php echo $point['delivery_zone_id']; ?>.setMap(map);


    //var center = poly<?php echo $point['delivery_zone_id']; ?>.getBounds().getCenter();

    //map.fitBounds(poly<?php echo $point['delivery_zone_id']; ?>.getBounds());


    //Define position of label
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < coord<?php echo $point['delivery_zone_id']; ?>.length; i++) {
        bounds.extend(coord<?php echo $point['delivery_zone_id']; ?>[i]);
    }

    var myLatlng<?php echo $point['delivery_zone_id']; ?> = bounds.getCenter();

    var mapLabel<?php echo $point['delivery_zone_id']; ?> = new MapLabel({
        text: '<?php echo $point['delivery_cost']; ?>',
        position: myLatlng<?php echo $point['delivery_zone_id']; ?>,
        map: map,
        fontSize: 20,
        align: 'left'
    });
    mapLabel<?php echo $point['delivery_zone_id']; ?>.set('position', myLatlng<?php echo $point['delivery_zone_id']; ?>);
    var obj = {};
    obj.poly = poly<?php echo $point['delivery_zone_id']; ?>;
    obj.label = mapLabel<?php echo $point['delivery_zone_id']; ?>;
    gpolygons.push(obj);



    <?php } } ?>



    google.maps.event.addListener(map, "idle", function()
    {
        google.maps.event.trigger(map, 'resize');
    });
  }  

</script>

0

你添加了吗?

zoom: 10,
center: myLatlng,

为您的标记对象

(或者)

// map: an instance of GMap3
// latlng: an array of instances of GLatLng
var latlngbounds = new google.maps.LatLngBounds();
latlng.each(function(n){
   latlngbounds.extend(n);
});
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 

0

对于 Android/Java,没有必要自己发明算法,JTS 是这种功能的包。

                // use jts to get suitable coordinate for label inside polygon

            // convert google maps latlong to jts coordinates
            List<Coordinate> jtsCoordinateList = new ArrayList<>();

            for (LatLng gMapLatLng : polygon.getPoints())
                jtsCoordinateList.add(new Coordinate(gMapLatLng.latitude, gMapLatLng.longitude));
            Coordinate[] jtsCoordinateArray = jtsCoordinateList.toArray(new Coordinate[0]);


            // create jts polygon
            Geometry jtsGeometry = new GeometryFactory().createPolygon(jtsCoordinateArray);

            // initiate InteriorPointArea
            InteriorPointArea interiorPointArea = new InteriorPointArea(jtsGeometry);

            // use InteriorPointArea to get the coordinate
            Coordinate jtsInteriorPoint = interiorPointArea.getInteriorPoint();

            // convert jts coordinate to google maps coordinate
            LatLng polygonPoint = new LatLng(jtsInteriorPoint.getX(), jtsInteriorPoint.getY());

            // use the calculated coordinate to place a marker
            marker = createViewMarker(context, map, polygonPoint, legend);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接