无法在Google地图上显示多边形

时间:2013-04-20 11:13:07

标签: javascript jquery google-maps-api-3

我尝试使用Chrome和JSLint调试此代码4天,没有任何希望。我的代码应在Google地图上显示2个区域,以RegionID

分隔

我的HTML

<body>
    <div id="map_canvas" style="width: 100%; height: 100%;"></div>            

<script type="text/javascript"
    src="https://maps.googleapis.com/maps/api/js?sensor=false&region=vi&language=vi">
</script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    var map;

    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(10.79, 826.694),
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
    }
</script>

<script type="text/javascript">
    $(document).ready(function () {        
        initialize();
        var model =  [{"ID":946,"Latitude":10.7654200827348,"Longitude":106.681716282384,"RegionID":80},{"ID":947,"Latitude":10.7563117596896,"Longitude":106.685397072824,"RegionID":80},{"ID":948,"Latitude":10.7537788369752,"Longitude":106.68713674361,"RegionID":80},
{"ID":1271,"Latitude":10.8577143149377,"Longitude":106.657884916756,"RegionID":82},{"ID":1272,"Latitude":10.8576257110992,"Longitude":106.657710314914,"RegionID":82},{"ID":1273,"Latitude":10.8575762617472,"Longitude":106.657500586099,"RegionID":82},{"ID":1274,"Latitude":10.8575794962578,"Longitude":106.657309632748,"RegionID":82},{"ID":1275,"Latitude":10.8576187762307,"Longitude":106.65709567219,"RegionID":82}]      
        polygon(model);        
    });
</script>

这是我的polygon功能

// Take an array of objects that have lat and lon attribute
function polygon(polygonCoords) {    
    // Initialize    
    // First dimension
    var id = polygonCoords[0].RegionID;
    var long;
    var lat;
    var region = new Array();
    for (var i = 0; i < polygonCoords.length; i++) {
        if ((id != polygonCoords[i].RegionID) || (i == polygonCoords.length - 1)) {
            // Draw polygon
            // Set path to a polygon along with polygon's option                

            var regionPolygon = new google.maps.Polygon({
                paths: region,
                fillColor: "#0000A0",                
                editable: false,                
            });


            // Set to map
            regionPolygon.setMap(map);

            // Reset stuffs
            region.length = 0;
            id = polygonCoords[i].RegionID;
        }
        long = polygonCoords[i].Longitude;
        lat = polygonCoords[i].Latitude;
        region.push(new google.maps.LatLng(lat, long));
    }
}

我收到的只是一张没有任何多边形的Google地图。我尝试删除for循环并按一个变量推送到region数组,它再次起作用。这很荒谬,但这是我4天后想到的。 谢谢

1 个答案:

答案 0 :(得分:1)

我无法告诉你那里发生了什么,但是当我替换它时,它对我有用

region.length=0;

region=[];