也许以下内容会有所帮助。我稍微重新安排了一些东西,做了一些小的修改,但基本上是一样的。在原版中,您在声明 outerCoords 之前将其作为值调用,所以我想控制台中存在错误。
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Google Maps: </title>
<style>
#mapSect{
width:100%;
height:100vh;
float:none;
margin:auto;
}
</style>
<script>
function initMap(){
// It is unclear where "selectedFullAddress" is defined hence manually assigning here.
const selectedFullAddress='Jalan Chengal, Kampung Melayu Subang, 40150 Shah Alam, Selangor, Malaysia';
const map = new google.maps.Map( document.getElementById("mapSect"), {
center: { lat:3.528319665937775, lng:101.7580347776062 },
zoom: 5
});
const geocoder = new google.maps.Geocoder();
// very basic function to add simple marker to aid visualisation
const addmarker=function( pos,i ){
let marker=new google.maps.Marker({
position:pos,
title:i + ' [ '+pos+' ]',
map:map,
draggable:true
});
return marker;
};
let bounds=new google.maps.LatLngBounds();
var outerCoords =[
{lat:3.326413,lng:101.258009},
{lat:3.388127,lng:101.787869},
{lat:2.9951223092598767,lng:101.82611927913445},
{lat:3.003044444012029,lng:101.4085838669952},
];
var rightShoulderFront = new google.maps.Polygon({
paths: outerCoords,
strokeColor: '#0000CC',
strokeOpacity: 0.5,
strokeWeight:1,
fillColor:'red',
fillOpacity:0.25
});
// iterate over coordinates and extend the bounds object
outerCoords.forEach( (obj,i)=>{
bounds.extend(obj);
});
map.fitBounds( bounds );
rightShoulderFront.setMap( map );
geocoder.geocode({ address: selectedFullAddress },function(results,status){
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
var curPosition = new google.maps.LatLng(lat,lng);
var isWithinPolygon = google.maps.geometry.poly.containsLocation(curPosition, rightShoulderFront)
if( isWithinPolygon ) addmarker( curPosition, 'Found Address: '+isWithinPolygon )
console.info(results,isWithinPolygon,status)
});
}
</script>
<script async defer src='//maps.googleapis.com/maps/api/js?key=<APIKEY>&callback=initMap'></script>
</head>
<body>
<div id='mapSect'></div>
</body>
</html>