为每个多边形打开信息窗口谷歌地图 V3

问题描述 投票:0回答:3

希望有人能帮我解决这个问题。 我正在尝试为我的用户创建的每个多边形点击打开一个信息窗口。 我对标记使用了相同的代码并且效果很好,但我无法使其适用于每个多边形。

关于如何解决这个问题有什么想法吗?

var contentString = '<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h2>Test</h2>'+
    '</div>';

var infowindow = new google.maps.InfoWindow({
    content: contentString
});

// 展示区

<?php foreach ($field->result() as $f):?>

// Create an array with the coordanates of each area

var field<?=$f->id?>Coords = [
    <?php $latlng=$this->resources_data->field_latlng($f->id);?>
    <?php foreach ($latlng->result() as $point):?>
    new google.maps.LatLng(<?=$point->lat?>, <?=$point->lng?>),
    <?php endforeach;?>
];

// Create a polygon with the points of the area

var area<?=$f->id?>=new google.maps.Polygon({
    paths: area<?=$f->id?>Coords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
});

// Add the area to the map.

area<?=$f->id?>.setMap(map);

google.maps.event.addListener(area<?=$f->id?>,'click',function(){
    infowindow.open(map,area<?=$f->id?>)
});

<?php endforeach;?>
google-maps-api-3 polygon infowindow
3个回答
26
投票

您不能对多边形使用与标记相同的形式 InfoWindow.open(没有要传入的标记)。

来自文档

open(map?:Map|StreetViewPanorama, anchor?:MVCObject)

返回值:无

在给定地图上打开此信息窗口。可选地,InfoWindow 可以与锚关联。 在核心 API 中,唯一的锚点是 Marker 类。 但是,锚点可以是任何公开 LatLng 位置属性和可选的 Point anchorPoint 属性以计算 pixelOffset 的 MVCObject(请参阅 InfoWindowOptions)。 anchorPoint 是从锚点位置到 InfoWindow 尖端的偏移量。)

需要在调用open方法时具体设置要打开的位置(点击的latlng通常是个不错的选择)用InfoWindow.setPosition()。

例子

代码片段:

var infowindow = new google.maps.InfoWindow({
  size: new google.maps.Size(150, 50)
});


function initialize() {
  var geolib = google.maps.geometry.spherical;
  var myOptions = {
    zoom: 20,
    center: new google.maps.LatLng(32.738158, -117.14874),
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

  google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
  });
  bounds = new google.maps.LatLngBounds();

  var polygon1 = new google.maps.Polygon({
    map: map,
    path: [geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 0),
      geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 120),
      geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, -120)
    ],
    name: "polygon1"
  });
  google.maps.event.addListener(polygon1, 'click', function(event) {
    var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
    infowindow.setContent(contentString);
    infowindow.setPosition(event.latLng);
    infowindow.open(map);
  });
  for (var i = 0; i < polygon1.getPath().getLength(); i++) {
    bounds.extend(polygon1.getPath().getAt(i));
  }
  var polygon2 = new google.maps.Polygon({
    map: map,
    path: [geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 180),
      geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 60),
      geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, -60)
    ],
    name: "polygon2"
  });
  google.maps.event.addListener(polygon2, 'click', function(event) {
    var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
    infowindow.setContent(contentString);
    infowindow.setPosition(event.latLng);
    infowindow.open(map);
  });
  for (var i = 0; i < polygon2.getPath().getLength(); i++) {
    bounds.extend(polygon2.getPath().getAt(i));
  }

  map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);

function createClickablePoly(poly, html, label, point) {
  gpolys.push(poly);
  if (!point && poly.getPath && poly.getPath().getLength && (poly.getPath().getLength > 0) && poly.getPath().getAt(0)) {
    point = poly.getPath().getAt(0);
  }
  var poly_num = gpolys.length - 1;
  if (!html) {
    html = "";
  } else {
    html += "<br>";
  }
  var length = poly.Distance();
  if (length > 1000) {
    html += "length=" + poly.Distance().toFixed(3) / 1000 + " km";
  } else {
    html += "length=" + poly.Distance().toFixed(3) + " meters";
  }
  for (var i = 0; i < poly.getPath().getLength(); i++) {
    html += "<br>poly[" + poly_num + "][" + i + "]=" + poly.getPath().getAt(i);
  }
  html += "<br>Area: " + poly.Area() + " sq meters";
  // html += poly.getLength().toFixed(2)+" m; "+(poly.getLength()*3.2808399).toFixed(2)+" ft; ";
  // html += (poly.getLength()*0.000621371192).toFixed(2)+" miles";
  var contentString = html;
  google.maps.event.addListener(poly, 'click', function(event) {
    infowindow.setContent(contentString);
    if (event) {
      point = event.latLng;
    }
    infowindow.setPosition(point);
    infowindow.open(map);
    // map.openInfoWindowHtml(point,html); 
  });
  if (!label) {
    label = "polyline #" + poly_num;
  }
  label = "<a href='javascript:google.maps.event.trigger(gpolys[" + poly_num + "],\"click\");'>" + label + "</a>";
  // add a line to the sidebar html
  //  side_bar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />';
}
body,
html {
  height: 100%;
  width: 100%;
}
<script src="https://maps.google.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="1" style="height:100%; width:100%">
  <tr>
    <td>
      <div id="map_canvas" style="width:100%; height:100%"></div>
    </td>
    <td width="200">
      <div id="report"></div>
    </td>
  </tr>
</table>


1
投票
<script>

function initMap() {
         var map = new google.maps.Map(document.getElementById('map'), {
             zoom: 12,
             center: {lat: 45.15492713361847, lng: 15.40557861328125}
         });

         var polygons = [{name: 'first name', coordinates:[{lat:45.15492713361847,lng:15.40557861328125},{lat:45.07933920973809,lng:15.5291748046875},{lat:45.01918507438175,lng:15.43304443359375},{lat:45.07933920973809,lng:15.3204345703125}]}];

            // foreach your polygons
            for (var i = 0; i < polygons.length; i++) {
                var item = polygons[i];

                var coors = item["coordinates"];
                var name = item["name"];


                var Polygon = new google.maps.Polygon({
                    path: coors,
                    strokeColor: '#66b3ff',
                    strokeOpacity: 0.8,
                    strokeWeight: 5,
                    editable: false,
                    fillColor: 'blue',
                    fillOpacity: 0.5,
                });
                Polygon.setMap(map);

                // call function to set window
                attachPolygonInfoWindow(Polygon, coors, name);
            }
        }

        function attachPolygonInfoWindow(polygon, coors, html)
        {

            polygon.infoWindow = new google.maps.InfoWindow({
                content: html
            });

            polygon.infoWindow.setPosition(getHighestWindowPosition(coors));

            google.maps.event.addListener(polygon, 'mouseover', function () {
                polygon.infoWindow.open(map, polygon);
            });
            google.maps.event.addListener(polygon, 'mouseout', function () {
                polygon.infoWindow.close();
            });
        }

        // function to get highest position of polygon to show window nice on top 
        function getHighestWindowPosition(coors) {

            var lat = -5000, lng = 0, i = 0, n = coors.length;

            for (; i !== n; ++i) {
                if (coors[i].lat > lat) {
                    lat = coors[i].lat;
                    lng = coors[i].lng;
                }
            }
            return  {lat: lat, lng: lng};

        }

</script>

0
投票
            function loadPolygons() {
                if (gup('ProjectID') > 0) {
                    $.ajax({
                        url: "api/Polygon/GetForProject?ProjectID=" + gup('ProjectID'),
                        contentType: 'application/json',
                        success: function (data) {
                            for (var i = 0; i < data.length; i++) {
                                var bounds = new google.maps.LatLngBounds();

                                if (data[i].Shape.length > 0) {
                                    //alert(data[i].Shape);
                                    var myPath = JSON.parse(data[i].Shape);
                                    let latLngArray = [];
                                    for (let i = 0; i < myPath.length; i++) {
                                        latLngArray.push(new google.maps.LatLng(myPath[i].lat,
                                            myPath[i].lng))
                                    }

                                    var poly = new google.maps.Polygon({
                                        paths: latLngArray,
                                        editable: false,
                                        draggable: false,
                                        clickable: true,
                                        strokeColor: '#FF0000',
                                        strokeOpacity: 0.7,
                                        strokeWeight: 2,
                                        fillColor: '#FF0000',
                                        fillOpacity: 0.25,
                                        map: map
                                    });

                                    for (var pathidx = 0; pathidx < poly.getPath().getLength(); pathidx++) {
                                        bounds.extend(poly.getPath().getAt(pathidx));
                                    }
                                    // store the computed center as a property of the polygon for easy access
                                    poly.center = bounds.getCenter();

                                    var infowindow = new google.maps.InfoWindow();
                                    var contentString = "<div class='infoBox'><strong>Roster Date:" + data[i].RosterDateString + "</strong><br>Field Activity: " + data[i].FieldActivityDescription + "<br>View <a href='CrewRosterDetail.aspx?CrewRosterID=" + data[i].CrewRosterID + "' target='_blank'>Crew Roster</a><br><img width='150px' src='./GetProjectActivityPhoto.ashx?CrewRosterID=" + data[i].CrewRosterID + "'/></div>";

                                    // use function closure to associate the infowindow with the polygon
                                    poly.addListener('click', (function (content) {
                                    return function () {
                                        // set the content
                                        infowindow.setContent(content);
                                        // set the position
                                        infowindow.setPosition(this.center);
                                        // open it
                                        infowindow.open(map);
                                    }
                                    })(contentString));

                                    map.setZoom(18);
                                }
                            }
                        },
                        error: function (request, status, error) {
                            alert(msg.ExceptionMessage);
                        }
                    });
                }
                else {
                    alert("Please save the Project and some project activities before attempting to display polygons!");
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.