2016-06-30 55 views
-1

我用Google Maps API製作了一個網站。如果用戶點擊多邊形,則會出現一條消息。它在點擊時起作用,所以用戶必須點擊Polygon區域內外,但是我想根據用戶當前的位置在頁面加載時進行。Javascript - Trigger點擊頁面加載

是否有可能在頁面加載時觸發以下功能?

google.maps.event.addListener(map, 'click', function (event) { 
     if (boundaryPolygon!=null && boundaryPolygon.Contains(event.latLng)) { 
      document.getElementById('result').innerHTML = 'You live in this area.'; 
     } else { 
      //alert(event.latLng + " Du bist ein Ossi!"); 
      document.getElementById('result').innerHTML = 'You live outside this area.'; 
     } 

    }); 
} 
+2

您不能將所有代碼移動到不同的函數中,並從該監聽器和加載事件中調用該函數嗎? –

+0

如果我這樣做,整個腳本不再工作。它需要點擊才能工作。點擊Google Map將位置傳遞給腳本。 – Matthijs

+0

你可以將你的整個'click'函數放入函數中,並將其命名爲'function showArea(event){// if ... else ...}'。然後添加事件監聽器('addListener(map,'click',showArea(event));'),並在map ready事件中運行'showArea()'函數(我認爲maps api有一些事件發生時地圖加載) –

回答

0

可以觸發地圖這樣上的click事件(其中latLng屬性,是點擊的位置):

google.maps.event.trigger(map, 'click', { 
    latLng: new google.maps.LatLng(24.886, -70.268) 
}); 

proof of concept fiddle

代碼片段:

// polygon example from: https://developers.google.com/maps/documentation/javascript/examples/polygon-simple 
 
// This example creates a simple polygon representing the Bermuda Triangle. 
 

 
function initMap() { 
 
    var map = new google.maps.Map(document.getElementById('map'), { 
 
    zoom: 5, 
 
    center: { 
 
     lat: 24.886, 
 
     lng: -70.268 
 
    }, 
 
    mapTypeId: google.maps.MapTypeId.TERRAIN 
 
    }); 
 

 
    // Define the LatLng coordinates for the polygon's path. 
 
    var triangleCoords = [{ 
 
    lat: 25.774, 
 
    lng: -80.190 
 
    }, { 
 
    lat: 18.466, 
 
    lng: -66.118 
 
    }, { 
 
    lat: 32.321, 
 
    lng: -64.757 
 
    }, { 
 
    lat: 25.774, 
 
    lng: -80.190 
 
    }]; 
 

 
    // Construct the polygon. 
 
    var boundaryPolygon = new google.maps.Polygon({ 
 
    paths: triangleCoords, 
 
    strokeColor: '#FF0000', 
 
    strokeOpacity: 0.8, 
 
    strokeWeight: 2, 
 
    fillColor: '#FF0000', 
 
    fillOpacity: 0.35, 
 
    clickable: false 
 
    }); 
 
    boundaryPolygon.setMap(map); 
 
    google.maps.event.addListener(map, 'click', function(event) { 
 
    if (boundaryPolygon != null && google.maps.geometry.poly.containsLocation(event.latLng, boundaryPolygon)) { 
 
     document.getElementById('result').innerHTML = 'You live in this area.'; 
 
    } else { 
 
     document.getElementById('result').innerHTML = 'You live outside this area.'; 
 
    } 
 
    }); 
 
    google.maps.event.trigger(map, 'click', { 
 
    latLng: new google.maps.LatLng(24.886, -70.268) 
 
    }); 
 
}
html, 
 
body { 
 
    height: 100%; 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
#map { 
 
    height: 100%; 
 
}
<div id="result"></div> 
 
<div id="map"></div> 
 
<!-- Replace the value of the key parameter with your own API key. --> 
 
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=geometry&callback=initMap"> 
 
</script>