คุณเพิ่มรูปร่างต่างๆ ลงในแผนที่ได้ รูปร่างคือออบเจ็กต์บนแผนที่ซึ่งเชื่อมโยงกับพิกัดละติจูด/ลองจิจูด รูปร่างที่ใช้ได้มีดังนี้ เส้น รูปหลายเหลี่ยม วงกลม และสี่เหลี่ยมผืนผ้า นอกจากนี้ คุณยังกำหนดค่ารูปร่างเพื่อให้ผู้ใช้แก้ไขหรือลากรูปร่าง หรือรวมรูปร่างเข้ากับไลบรารีเรขาคณิต (google.maps.GeometryLibrary) เพื่อตรวจสอบเขตพื้นที่เสมือนและขอบเขตโซนปลอดภัยได้ด้วย
เส้นประกอบ
หากต้องการวาดเส้นบนแผนที่ ให้ใช้เส้นประกอบ คลาส
Polyline กำหนดการวางซ้อนเชิงเส้นของส่วนของเส้นที่เชื่อมต่อกันบนแผนที่ ออบเจ็กต์ Polyline ประกอบด้วยอาร์เรย์ของตำแหน่ง LatLng และสร้างชุดของส่วนของเส้นตรงที่เชื่อมต่อตำแหน่งเหล่านั้นตามลำดับที่เรียงไว้
เพิ่มเส้นประกอบ
ตัวสร้าง Polyline จะใช้ชุด PolylineOptions ที่ระบุพิกัด LatLng ของเส้นและชุดสไตล์เพื่อปรับลักษณะการแสดงผลของเส้นประกอบ
ระบบจะวาดออบเจ็กต์ Polyline เป็นชุดของส่วนตรงบนแผนที่ คุณสามารถระบุสีแบบกำหนดเอง ความหนา และความทึบแสงสำหรับเส้นขีดของเส้นภายใน PolylineOptions เมื่อสร้างเส้น หรือจะเปลี่ยนพร็อพเพอร์ตี้เหล่านั้นหลังจากสร้างก็ได้
เส้นประกอบรองรับรูปแบบเส้นต่อไปนี้
strokeColorระบุสี HTML เลขฐาน 16 ของรูปแบบ"#FFFFFF"คลาสPolylineไม่รองรับสีที่มีชื่อstrokeOpacityระบุค่าตัวเลขระหว่าง0.0ถึง1.0เพื่อกำหนดความทึบแสงของสีเส้น ค่าเริ่มต้นคือ1.0strokeWeightระบุความกว้างของเส้นเป็นพิกเซล
พร็อพเพอร์ตี้ editable ของเส้นประกอบจะระบุว่าผู้ใช้แก้ไขรูปร่างได้หรือไม่ ดูรูปร่างที่ผู้ใช้แก้ไขได้ด้านล่าง ในทำนองเดียวกัน คุณสามารถตั้งค่าพร็อพเพอร์ตี้ draggable เพื่ออนุญาตให้ผู้ใช้ลากเส้นได้
ตัวอย่างนี้สร้างเส้นประกอบสีแดงกว้าง 2 พิกเซลซึ่งแสดงเส้นทางของเที่ยวบินข้ามมหาสมุทรแปซิฟิกเที่ยวบินแรกระหว่างโอ๊คแลนด์ รัฐแคลิฟอร์เนียกับบริสเบน ประเทศออสเตรเลีย
TypeScript
// This example creates a 2-pixel-wide red polyline showing the path of // the first trans-Pacific flight between Oakland, CA, and Brisbane, // Australia which was made by Charles Kingsford Smith. const mapElement = document.querySelector('gmp-map')!; let innerMap: google.maps.Map; async function init() { const { Polyline } = await google.maps.importLibrary('maps'); innerMap = mapElement.innerMap; const flightPlanCoordinates = [ { lat: 37.772, lng: -122.214 }, { lat: 21.291, lng: -157.821 }, { lat: -18.142, lng: 178.431 }, { lat: -27.467, lng: 153.027 }, ]; const flightPath = new Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(innerMap); } void init();
JavaScript
// This example creates a 2-pixel-wide red polyline showing the path of // the first trans-Pacific flight between Oakland, CA, and Brisbane, // Australia which was made by Charles Kingsford Smith. const mapElement = document.querySelector('gmp-map'); let innerMap; async function init() { const { Polyline } = await google.maps.importLibrary('maps'); innerMap = mapElement.innerMap; const flightPlanCoordinates = [ { lat: 37.772, lng: -122.214 }, { lat: 21.291, lng: -157.821 }, { lat: -18.142, lng: 178.431 }, { lat: -27.467, lng: 153.027 }, ]; const flightPath = new Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(innerMap); } void init();
นำเส้นประกอบออก
หากต้องการนำเส้นประกอบออกจากแผนที่ ให้เรียกใช้เมธอด setMap() โดยส่ง null เป็นอาร์กิวเมนต์ ในตัวอย่างต่อไปนี้ flightPath เป็นออบเจ็กต์เส้นประกอบ
flightPath.setMap(null);
โปรดทราบว่าวิธีการข้างต้นไม่ได้ลบเส้นประกอบ ซึ่งจะนำเส้นประกอบออกจากแผนที่ หากต้องการลบเส้นประกอบแทน คุณควรนำเส้นประกอบออกจากแผนที่ แล้วตั้งค่าเส้นประกอบเป็น null
ตรวจสอบเส้นประกอบ
เส้นประกอบจะระบุชุดพิกัดเป็นอาร์เรย์ของออบเจ็กต์ LatLng พิกัดเหล่านี้จะกำหนดเส้นทางของเส้น
หากต้องการดึงข้อมูลพิกัด ให้เรียกใช้ getPath() ซึ่งจะแสดงผลอาร์เรย์ประเภท MVCArray คุณสามารถจัดการและตรวจสอบอาร์เรย์ได้โดยใช้การดำเนินการต่อไปนี้
getAt()แสดงผลLatLngที่ค่าดัชนีแบบอิงตามเลขศูนย์ที่ระบุinsertAt()แทรกLatLngที่ส่งมาที่ค่าดัชนีแบบ 0 ที่ระบุ โปรดทราบว่าพิกัดที่มีอยู่ซึ่งมีค่าดัชนีนั้นจะถูกเลื่อนไปข้างหน้าremoveAt()นำLatLngออกที่ค่าดัชนีแบบอิงตามเลขศูนย์ที่ระบุ
ตัวอย่างต่อไปนี้แสดงการสร้างเส้นประกอบตามการคลิก (คลิกแผนที่เพื่อเพิ่มจุดยอด)
TypeScript
/** * This example creates an interactive map which constructs a polyline based on * user clicks. Note that the polyline only appears once its path property * contains two LatLng coordinates. */ let poly: google.maps.Polyline; const mapElement = document.querySelector('gmp-map')!; let innerMap: google.maps.Map; async function init() { // Import the needed libraries. const [{ Polyline }, { AdvancedMarkerElement }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('marker'), ]); innerMap = mapElement.innerMap; poly = new Polyline({ strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 3, }); poly.setMap(innerMap); // Handles click events on a map, and adds a new point to the Polyline. innerMap.addListener('click', (event: google.maps.MapMouseEvent) => { const latLng = event.latLng; if (!latLng) return; const path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear. path.push(latLng); // Add a new marker at the new plotted point on the polyline. new AdvancedMarkerElement({ position: latLng, title: '#' + path.getLength(), map: innerMap, }); }); } void init();
JavaScript
/** * This example creates an interactive map which constructs a polyline based on * user clicks. Note that the polyline only appears once its path property * contains two LatLng coordinates. */ let poly; const mapElement = document.querySelector('gmp-map'); let innerMap; async function init() { // Import the needed libraries. const [{ Polyline }, { AdvancedMarkerElement }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('marker'), ]); innerMap = mapElement.innerMap; poly = new Polyline({ strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 3, }); poly.setMap(innerMap); // Handles click events on a map, and adds a new point to the Polyline. innerMap.addListener('click', (event) => { const latLng = event.latLng; if (!latLng) return; const path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear. path.push(latLng); // Add a new marker at the new plotted point on the polyline. new AdvancedMarkerElement({ position: latLng, title: '#' + path.getLength(), map: innerMap, }); }); } void init();
ปรับแต่งเส้นประกอบ
คุณสามารถเพิ่มรูปภาพแบบเวกเตอร์ลงในเส้นประกอบในรูปแบบของสัญลักษณ์ได้ เมื่อใช้สัญลักษณ์ร่วมกับคลาส PolylineOptions คุณจะควบคุมรูปลักษณ์ของเส้นประกอบบนแผนที่ได้เป็นอย่างมาก
ดูข้อมูลเกี่ยวกับลูกศร เส้นประ สัญลักษณ์ที่กำหนดเอง และสัญลักษณ์แบบเคลื่อนไหวได้ที่สัญลักษณ์
รูปหลายเหลี่ยม
รูปหลายเหลี่ยมแสดงถึงพื้นที่ที่ล้อมรอบด้วยเส้นทางปิด (หรือลูป) ซึ่งกำหนดโดยชุดพิกัด
Polygon ออบเจ็กต์คล้ายกับออบเจ็กต์ Polyline ตรงที่ประกอบด้วยชุดพิกัดตามลำดับ
รูปหลายเหลี่ยมจะวาดด้วยเส้นและสีเติม คุณสามารถกำหนดสีแบบกำหนดเอง ความหนา และความทึบแสงสำหรับขอบของรูปหลายเหลี่ยม (เส้นขอบ) รวมถึงสีแบบกำหนดเองและความทึบแสงสำหรับพื้นที่ที่ล้อมรอบ (สีเติม) โดยควรระบุสีในรูปแบบ HTML เลขฐาน 16 ระบบไม่รองรับชื่อสี
ออบเจ็กต์ Polygon สามารถอธิบายรูปร่างที่ซับซ้อนได้ ซึ่งรวมถึงสิ่งต่อไปนี้
- พื้นที่หลายแห่งที่ไม่ติดกันซึ่งกำหนดโดยรูปหลายเหลี่ยมเดียว
- พื้นที่ที่มีรู
- จุดตัดของพื้นที่อย่างน้อย 1 แห่ง
หากต้องการกำหนดรูปร่างที่ซับซ้อน ให้ใช้รูปหลายเหลี่ยมที่มีหลายเส้นทาง
หมายเหตุ: ชั้นข้อมูลเป็นวิธีง่ายๆ ในการวาดรูปหลายเหลี่ยม โดยจะจัดการการหมุนรูปหลายเหลี่ยมให้คุณ ซึ่งช่วยให้วาดรูปหลายเหลี่ยมที่มีรูได้ง่ายขึ้น ดูเอกสารประกอบสำหรับชั้นข้อมูล
เพิ่มรูปหลายเหลี่ยม
เนื่องจากพื้นที่รูปหลายเหลี่ยมอาจมีเส้นทางแยกกันหลายเส้นทาง พร็อพเพอร์ตี้ paths ของออบเจ็กต์ Polygon จึงระบุอาร์เรย์ของอาร์เรย์ ซึ่งแต่ละอาร์เรย์เป็นประเภท MVCArray แต่ละอาร์เรย์จะกำหนดลำดับพิกัด LatLng ที่เรียงลำดับแยกกัน
สำหรับรูปหลายเหลี่ยมแบบง่ายที่ประกอบด้วยเส้นทางเดียว คุณสามารถสร้าง Polygon โดยใช้อาร์เรย์เดียวของพิกัด LatLng Maps JavaScript API จะแปลงอาร์เรย์แบบง่ายเป็นอาร์เรย์ของอาร์เรย์เมื่อสร้างขึ้นเมื่อจัดเก็บไว้ในพร็อพเพอร์ตี้ paths API มีเมธอด getPath() แบบง่ายสำหรับรูปหลายเหลี่ยมที่ประกอบด้วยเส้นทางเดียว
พร็อพเพอร์ตี้ editable ของรูปหลายเหลี่ยมจะระบุว่าผู้ใช้แก้ไขรูปร่างได้หรือไม่ ดูรูปร่างที่ผู้ใช้แก้ไขได้ด้านล่าง
ในทำนองเดียวกัน คุณสามารถตั้งค่าพร็อพเพอร์ตี้ draggable เพื่ออนุญาตให้ผู้ใช้ลากรูปร่างได้
TypeScript
// This example creates a simple polygon representing the Bermuda Triangle. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", } ); // Define the LatLng coordinates for the polygon's path. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, { lat: 25.774, lng: -80.19 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a simple polygon representing the Bermuda Triangle. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", }); // Define the LatLng coordinates for the polygon's path. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, { lat: 25.774, lng: -80.19 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } window.initMap = initMap;
การเติมรูปหลายเหลี่ยมอัตโนมัติ
Polygon ในตัวอย่างด้านบนประกอบด้วยพิกัด LatLng 4 ชุด แต่โปรดสังเกตว่าชุดแรกและชุดสุดท้ายกำหนดตำแหน่งเดียวกัน ซึ่งทำให้ลูปสมบูรณ์ อย่างไรก็ตาม ในทางปฏิบัติ เนื่องจากรูปหลายเหลี่ยมกำหนดพื้นที่ปิด คุณจึงไม่จำเป็นต้องระบุชุดพิกัดสุดท้าย Maps JavaScript API จะสร้างรูปหลายเหลี่ยมให้เสร็จสมบูรณ์โดยอัตโนมัติด้วยการวาดเส้นที่เชื่อมต่อตำแหน่งสุดท้ายกลับไปยังตำแหน่งแรกสำหรับเส้นทางที่ระบุ
ตัวอย่างต่อไปนี้เหมือนกับตัวอย่างก่อนหน้า ยกเว้นว่าไม่มี LatLng สุดท้าย: ดูตัวอย่าง
นำรูปหลายเหลี่ยมออก
หากต้องการนำรูปหลายเหลี่ยมออกจากแผนที่ ให้เรียกใช้เมธอด setMap() โดยส่ง null เป็นอาร์กิวเมนต์ ในตัวอย่างต่อไปนี้ bermudaTriangle เป็นออบเจ็กต์รูปหลายเหลี่ยม
bermudaTriangle.setMap(null);
โปรดทราบว่าวิธีการข้างต้นไม่ได้ลบรูปหลายเหลี่ยม ซึ่งจะนำรูปหลายเหลี่ยมออกจากแผนที่ หากต้องการลบรูปหลายเหลี่ยมแทน คุณควรนำรูปหลายเหลี่ยมออกจากแผนที่ แล้วตั้งค่ารูปหลายเหลี่ยมเป็น null
ตรวจสอบรูปหลายเหลี่ยม
รูปหลายเหลี่ยมจะระบุชุดพิกัดเป็นอาร์เรย์ของอาร์เรย์ โดยแต่ละอาร์เรย์เป็นประเภท MVCArray อาร์เรย์ "Leaf" แต่ละรายการคืออาร์เรย์ของพิกัด LatLng ที่ระบุเส้นทางเดียว หากต้องการดึงข้อมูลพิกัดเหล่านี้ ให้เรียกใช้เมธอด getPaths() ของออบเจ็กต์ Polygon เนื่องจากอาร์เรย์เป็น MVCArray คุณจึงต้องจัดการและตรวจสอบอาร์เรย์โดยใช้การดำเนินการต่อไปนี้
getAt()แสดงผลLatLngที่ค่าดัชนีแบบอิงตามเลขศูนย์ที่ระบุinsertAt()แทรกLatLngที่ส่งมาที่ค่าดัชนีแบบ 0 ที่ระบุ โปรดทราบว่าพิกัดที่มีอยู่ซึ่งมีค่าดัชนีนั้นจะถูกเลื่อนไปข้างหน้าremoveAt()นำLatLngออกที่ค่าดัชนีแบบอิงตามเลขศูนย์ที่ระบุ
TypeScript
// This example creates a simple polygon representing the Bermuda Triangle. // When the user clicks on the polygon an info window opens, showing // information about the polygon's coordinates. let map: google.maps.Map; let infoWindow: google.maps.InfoWindow; function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", }); // Define the LatLng coordinates for the polygon. const triangleCoords: google.maps.LatLngLiteral[] = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 3, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); // Add a listener for the click event. bermudaTriangle.addListener("click", showArrays); infoWindow = new google.maps.InfoWindow(); } function showArrays(event: any) { // Since this polygon has only one path, we can call getPath() to return the // MVCArray of LatLngs. // @ts-ignore const polygon = this as google.maps.Polygon; const vertices = polygon.getPath(); let contentString = "<b>Bermuda Triangle polygon</b><br>" + "Clicked location: <br>" + event.latLng.lat() + "," + event.latLng.lng() + "<br>"; // Iterate over the vertices. for (let i = 0; i < vertices.getLength(); i++) { const 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); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a simple polygon representing the Bermuda Triangle. // When the user clicks on the polygon an info window opens, showing // information about the polygon's coordinates. let map; let infoWindow; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", }); // Define the LatLng coordinates for the polygon. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 3, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); // Add a listener for the click event. bermudaTriangle.addListener("click", showArrays); infoWindow = new google.maps.InfoWindow(); } function showArrays(event) { // Since this polygon has only one path, we can call getPath() to return the // MVCArray of LatLngs. // @ts-ignore const polygon = this; const vertices = polygon.getPath(); let contentString = "<b>Bermuda Triangle polygon</b><br>" + "Clicked location: <br>" + event.latLng.lat() + "," + event.latLng.lng() + "<br>"; // Iterate over the vertices. for (let i = 0; i < vertices.getLength(); i++) { const 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); } window.initMap = initMap;
เจาะรูในรูปหลายเหลี่ยม
หากต้องการสร้างพื้นที่ว่างภายในรูปหลายเหลี่ยม คุณต้องสร้างเส้นทาง 2 เส้นทาง โดยเส้นทางหนึ่งอยู่ภายในอีกเส้นทางหนึ่ง หากต้องการสร้างรู พิกัดที่กำหนดเส้นทางด้านในต้องอยู่ในลำดับตรงกันข้ามกับพิกัดที่กำหนดเส้นทางด้านนอก เช่น หากพิกัดของเส้นทางด้านนอกอยู่ในลำดับตามเข็มนาฬิกา เส้นทางด้านในจะต้องทวนเข็มนาฬิกา
หมายเหตุ: ชั้นข้อมูลจะจัดการลำดับของเส้นทางด้านในและด้านนอกให้คุณ ซึ่งช่วยให้วาดรูปหลายเหลี่ยมที่มีรูได้ง่ายขึ้น ดูเอกสารประกอบสำหรับชั้นข้อมูล
ตัวอย่างต่อไปนี้จะวาดรูปหลายเหลี่ยมที่มี 2 เส้นทาง โดยเส้นทางด้านในจะหมุนไปในทิศทางตรงกันข้ามกับเส้นทางด้านนอก
TypeScript
// This example creates a triangular polygon with a hole in it. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, } ); // Define the LatLng coordinates for the polygon's outer path. const outerCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Define the LatLng coordinates for the polygon's inner path. // Note that the points forming the inner path are wound in the // opposite direction to those in the outer path, to form the hole. const innerCoords = [ { lat: 28.745, lng: -70.579 }, { lat: 29.57, lng: -67.514 }, { lat: 27.339, lng: -66.668 }, ]; // Construct the polygon, including both paths. const bermudaTriangle = new google.maps.Polygon({ paths: [outerCoords, innerCoords], strokeColor: "#FFC107", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FFC107", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a triangular polygon with a hole in it. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 5, center: { lat: 24.886, lng: -70.268 }, }); // Define the LatLng coordinates for the polygon's outer path. const outerCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Define the LatLng coordinates for the polygon's inner path. // Note that the points forming the inner path are wound in the // opposite direction to those in the outer path, to form the hole. const innerCoords = [ { lat: 28.745, lng: -70.579 }, { lat: 29.57, lng: -67.514 }, { lat: 27.339, lng: -66.668 }, ]; // Construct the polygon, including both paths. const bermudaTriangle = new google.maps.Polygon({ paths: [outerCoords, innerCoords], strokeColor: "#FFC107", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FFC107", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } window.initMap = initMap;
สี่เหลี่ยมผืนผ้า
นอกจากคลาส Polygon ทั่วไปแล้ว Maps JavaScript API ของ Google ยังมีคลาสเฉพาะสำหรับออบเจ็กต์
Rectangle เพื่อให้สร้างได้ง่ายขึ้น
เพิ่มสี่เหลี่ยมผืนผ้า
Rectangle คล้ายกับ Polygon ตรงที่คุณสามารถกำหนดสีแบบกำหนดเอง ความหนา และความทึบแสงที่กำหนดเองสำหรับขอบของสี่เหลี่ยมผืนผ้า (เส้นโครงร่าง) รวมถึงสีแบบกำหนดเองและความทึบแสงที่กำหนดเองสำหรับพื้นที่ภายในสี่เหลี่ยมผืนผ้า (การเติมสี) ควรระบุสีในรูปแบบ HTML ที่เป็นตัวเลขฐาน 16
คุณไม่ต้องกำหนด paths สำหรับ Rectangle ซึ่งต่างจาก Polygon แต่สี่เหลี่ยมผืนผ้าจะมีพร็อพเพอร์ตี้ bounds ซึ่งกำหนดรูปร่างโดยการระบุ
google.maps.LatLngBounds สำหรับสี่เหลี่ยมผืนผ้า
พร็อพเพอร์ตี้ editable ของสี่เหลี่ยมผืนผ้าจะระบุว่าผู้ใช้แก้ไขรูปร่างได้หรือไม่ ดูรูปร่างที่ผู้ใช้แก้ไขได้ด้านล่าง ในทำนองเดียวกัน คุณสามารถตั้งค่าพร็อพเพอร์ตี้ draggable เพื่ออนุญาตให้ผู้ใช้ลากสี่เหลี่ยมผืนผ้าได้
TypeScript
// This example adds a red rectangle to a map. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 11, center: { lat: 33.678, lng: -116.243 }, mapTypeId: "terrain", } ); const rectangle = new google.maps.Rectangle({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: { north: 33.685, south: 33.671, east: -116.234, west: -116.251, }, }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds a red rectangle to a map. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 11, center: { lat: 33.678, lng: -116.243 }, mapTypeId: "terrain", }); const rectangle = new google.maps.Rectangle({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: { north: 33.685, south: 33.671, east: -116.234, west: -116.251, }, }); } window.initMap = initMap;
โค้ดต่อไปนี้จะสร้างสี่เหลี่ยมผืนผ้าทุกครั้งที่ผู้ใช้เปลี่ยนการซูมบนแผนที่ ขนาดของสี่เหลี่ยมผืนผ้าจะกำหนดโดยวิวพอร์ต
TypeScript
// This example creates a rectangle based on the viewport // on any 'zoom-changed' event. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 11, center: { lat: 40.74852, lng: -73.981687 }, mapTypeId: "terrain", } ); const rectangle = new google.maps.Rectangle(); map.addListener("zoom_changed", () => { // Get the current bounds, which reflect the bounds before the zoom. rectangle.setOptions({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: map.getBounds() as google.maps.LatLngBounds, }); }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a rectangle based on the viewport // on any 'zoom-changed' event. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 11, center: { lat: 40.74852, lng: -73.981687 }, mapTypeId: "terrain", }); const rectangle = new google.maps.Rectangle(); map.addListener("zoom_changed", () => { // Get the current bounds, which reflect the bounds before the zoom. rectangle.setOptions({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: map.getBounds(), }); }); } window.initMap = initMap;
นำสี่เหลี่ยมผืนผ้าออก
หากต้องการนำสี่เหลี่ยมผืนผ้าออกจากแผนที่ ให้เรียกใช้เมธอด setMap() โดยส่ง null เป็นอาร์กิวเมนต์
rectangle.setMap(null);
โปรดทราบว่าวิธีการข้างต้นไม่ได้ลบสี่เหลี่ยมผืนผ้า ซึ่งจะนำสี่เหลี่ยมผืนผ้าออกจากแผนที่ หากต้องการลบสี่เหลี่ยมผืนผ้าแทน คุณควรนำสี่เหลี่ยมผืนผ้าออกจากแผนที่ แล้วตั้งค่าสี่เหลี่ยมผืนผ้าเป็น null
วงกลม
นอกจากคลาส Polygon ทั่วไปแล้ว Maps JavaScript API ของ Google ยังมีคลาสเฉพาะสำหรับออบเจ็กต์
Circle เพื่อให้สร้างได้ง่ายขึ้น
เพิ่มวงกลม
Circle มีลักษณะคล้ายกับ Polygon ตรงที่คุณสามารถกำหนดสีแบบกำหนดเอง ความหนา และความทึบแสงที่กำหนดเองสำหรับขอบของวงกลม (เส้นโครงร่าง) รวมถึงสีแบบกำหนดเองและความทึบแสงที่กำหนดเองสำหรับพื้นที่ภายในวงกลม (การเติม) ควรระบุสีในรูปแบบ HTML ที่เป็นตัวเลขฐาน 16
คุณไม่ต้องกำหนด paths สำหรับ Circle ซึ่งต่างจาก Polygon แต่วงกลมจะมีพร็อพเพอร์ตี้เพิ่มเติม 2 รายการที่กำหนดรูปร่าง ดังนี้
centerระบุgoogle.maps.LatLngของจุดศูนย์กลางของวงกลมradiusระบุรัศมีของวงกลมเป็นเมตร
พร็อพเพอร์ตี้ editable ของวงกลมจะระบุว่าผู้ใช้แก้ไขรูปร่างได้หรือไม่ ดูรูปร่างที่ผู้ใช้แก้ไขได้ด้านล่าง
ในทำนองเดียวกัน คุณสามารถตั้งค่าพร็อพเพอร์ตี้ draggable เพื่ออนุญาตให้ผู้ใช้ลากวงกลมได้
ตัวอย่างต่อไปนี้ใช้วงกลมเพื่อแสดงเวลาเดินโดยประมาณระหว่างสถานที่ต่างๆ ในเกียวโต ประเทศญี่ปุ่น เลือกระยะทางที่ต้องการจากเมนู คลิกแผนที่เพื่อปรับวงกลมให้อยู่ตรงกลางอีกครั้ง แล้วลากวงกลมเพื่อเปลี่ยนตำแหน่ง
TypeScript
const mapElement = document.querySelector('gmp-map')!; let innerMap: google.maps.Map; async function init() { // Request needed libraries. const [{ Circle }, { AdvancedMarkerElement }, { event }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('marker'), google.maps.importLibrary('core'), ]); // Set the initial map center point. const initialCenter = { lat: 34.98956821576194, lng: 135.74239981260283 }; // Hotel Emion, Kyoto, Japan // Get the inner map. innerMap = mapElement.innerMap; // Get the buttons. const buttons = document.querySelectorAll('input[name="radius"]'); // Create the circle. const walkingCircle = new Circle({ strokeColor: '#ffdd00ff', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#ffdd00ff', fillOpacity: 0.35, map: innerMap, center: initialCenter, radius: 400, draggable: true, editable: false, }); // Define a "Crosshair" vector icon const parser = new DOMParser(); const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="-6 -6 12 12"><path d="M -6,0 L 6,0 M 0,-6 L 0,6" stroke="black" stroke-width="1"/></svg>`; const pinSvg = parser.parseFromString( svgString, 'image/svg+xml' ).documentElement; const centerMarker = new AdvancedMarkerElement({ position: initialCenter, title: 'A marker using a custom SVG image.', anchorLeft: '-50%', anchorTop: '-50%', }); centerMarker.append(pinSvg); mapElement.append(centerMarker); // Wait for the map to finish drawing its tiles. event.addListenerOnce(innerMap, 'tilesloaded', () => { // Get the controls div const controls = document.getElementById('control-panel'); // Display controls once map is loaded. if (controls) { controls.style.display = 'block'; } }); // Add event listener to update the radius based on user selection. buttons.forEach((button) => { button.addEventListener('change', (changeEvent) => { const target = changeEvent.target as HTMLInputElement; walkingCircle.setRadius(Number(target.value)); }); }); // Handle user click, reset the map center and position the circle. innerMap.addListener( 'click', ( mapsMouseEvent: google.maps.MapMouseEvent | google.maps.IconMouseEvent ) => { const newCenter = mapsMouseEvent.latLng; if (!newCenter) return; walkingCircle.setCenter(newCenter); centerMarker.position = newCenter; innerMap.panTo(newCenter); } ); // Handle user dragging the circle, update the center marker position. walkingCircle.addListener('center_changed', () => { centerMarker.position = walkingCircle.getCenter(); }); } void init();
JavaScript
const mapElement = document.querySelector('gmp-map'); let innerMap; async function init() { // Request needed libraries. const [{ Circle }, { AdvancedMarkerElement }, { event }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('marker'), google.maps.importLibrary('core'), ]); // Set the initial map center point. const initialCenter = { lat: 34.98956821576194, lng: 135.74239981260283 }; // Hotel Emion, Kyoto, Japan // Get the inner map. innerMap = mapElement.innerMap; // Get the buttons. const buttons = document.querySelectorAll('input[name="radius"]'); // Create the circle. const walkingCircle = new Circle({ strokeColor: '#ffdd00ff', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#ffdd00ff', fillOpacity: 0.35, map: innerMap, center: initialCenter, radius: 400, draggable: true, editable: false, }); // Define a "Crosshair" vector icon const parser = new DOMParser(); const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="-6 -6 12 12"><path d="M -6,0 L 6,0 M 0,-6 L 0,6" stroke="black" stroke-width="1"/></svg>`; const pinSvg = parser.parseFromString( svgString, 'image/svg+xml' ).documentElement; const centerMarker = new AdvancedMarkerElement({ position: initialCenter, title: 'A marker using a custom SVG image.', anchorLeft: '-50%', anchorTop: '-50%', }); centerMarker.append(pinSvg); mapElement.append(centerMarker); // Wait for the map to finish drawing its tiles. event.addListenerOnce(innerMap, 'tilesloaded', () => { // Get the controls div const controls = document.getElementById('control-panel'); // Display controls once map is loaded. if (controls) { controls.style.display = 'block'; } }); // Add event listener to update the radius based on user selection. buttons.forEach((button) => { button.addEventListener('change', (changeEvent) => { const target = changeEvent.target; walkingCircle.setRadius(Number(target.value)); }); }); // Handle user click, reset the map center and position the circle. innerMap.addListener('click', (mapsMouseEvent) => { const newCenter = mapsMouseEvent.latLng; if (!newCenter) return; walkingCircle.setCenter(newCenter); centerMarker.position = newCenter; innerMap.panTo(newCenter); }); // Handle user dragging the circle, update the center marker position. walkingCircle.addListener('center_changed', () => { centerMarker.position = walkingCircle.getCenter(); }); } void init();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #control-panel { display: none; /* Set to 'display: block' after the map loads. */ background-color: #fff; border: 2px solid #fff; border-radius: 3px; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); font-family: 'Roboto', sans-serif; font-size: medium; margin: 10px; padding: 10px; }
HTML
<html>
<head>
<title>Circles</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<script>
// prettier-ignore
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "GOOGLE_MAPS_API_KEY"
});
</script>
</head>
<body>
<gmp-map
center="34.98956821576194, 135.74239981260283"
zoom="15"
map-id="DEMO_MAP_ID">
<div id="control-panel" slot="control-inline-start-block-start">
<input
id="short-walk"
type="radio"
name="radius"
value="400"
checked />
<label for="short-walk">Short Walk (~5 minutes)</label><br />
<input
id="medium-walk"
type="radio"
name="radius"
value="800" />
<label for="medium-walk">Medium Walk (~15 minutes)</label><br />
<input id="long-walk" type="radio" name="radius" value="1600" />
<label for="long-walk">Long Walk (~30 minutes) </label>
</div>
</gmp-map>
</body>
</html>นำแวดวงออก
หากต้องการนำวงกลมออกจากแผนที่ ให้เรียกใช้เมธอด setMap() โดยส่ง null เป็นอาร์กิวเมนต์
circle.setMap(null);
โปรดทราบว่าวิธีการข้างต้นไม่ได้ลบวงกลม ระบบจะนำวงกลมออกจากแผนที่ หากต้องการลบวงกลมแทน คุณควรนำวงกลมออกจากแผนที่ แล้วตั้งค่าวงกลมเป็น null
รูปร่างที่ผู้ใช้แก้ไขและลากได้
การทำให้รูปร่างแก้ไขได้จะเพิ่มแฮนเดิลลงในรูปร่าง ซึ่งผู้ใช้สามารถใช้เพื่อเปลี่ยนตำแหน่ง ปรับรูปร่าง และปรับขนาดรูปร่างบนแผนที่ได้โดยตรง นอกจากนี้ คุณยังทำให้รูปร่างลากได้เพื่อให้ผู้ใช้ย้ายไปยังตำแหน่งอื่นบนแผนที่ได้ด้วย
การเปลี่ยนแปลงที่ผู้ใช้ทำกับออบเจ็กต์จะไม่คงอยู่ระหว่างเซสชัน หากต้องการบันทึกการแก้ไขของผู้ใช้ คุณต้องบันทึกและจัดเก็บข้อมูลด้วยตนเอง
ทำให้รูปร่างแก้ไขได้
คุณสามารถตั้งค่ารูปร่างใดก็ได้ (เส้นประกอบ รูปหลายเหลี่ยม วงกลม และสี่เหลี่ยมผืนผ้า) ให้ผู้ใช้แก้ไขได้โดยตั้งค่า editable เป็น true ในตัวเลือกของรูปร่าง
var bounds = { north: 44.599, south: 44.490, east: -78.443, west: -78.649 }; // Define a rectangle and set its editable property to true. var rectangle = new google.maps.Rectangle({ bounds: bounds, editable: true });
ทำให้รูปร่างลากได้
โดยค่าเริ่มต้น รูปร่างที่วาดบนแผนที่จะได้รับการตรึงไว้ในตำแหน่งนั้นๆ หากต้องการอนุญาตให้ผู้ใช้ลากรูปร่างไปยังตำแหน่งอื่นบนแผนที่ ให้ตั้งค่า draggable เป็น true ในตัวเลือกรูปร่าง
var redCoords = [ {lat: 25.774, lng: -80.190}, {lat: 18.466, lng: -66.118}, {lat: 32.321, lng: -64.757} ]; // Construct a draggable red triangle with geodesic set to true. new google.maps.Polygon({ map: map, paths: redCoords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, draggable: true, geodesic: true });
เมื่อเปิดใช้การลากบนรูปหลายเหลี่ยมหรือเส้นประกอบ คุณควรพิจารณาสร้างรูปหลายเหลี่ยมหรือเส้นประกอบแบบจีโอเดสิกด้วย โดยตั้งค่าพร็อพเพอร์ตี้ geodesic เป็น true
รูปหลายเหลี่ยมแบบจีโอเดสิกจะคงรูปร่างทางภูมิศาสตร์ที่แท้จริงไว้เมื่อมีการย้าย ซึ่งทำให้รูปหลายเหลี่ยมดูบิดเบี้ยวเมื่อย้ายไปทางเหนือหรือใต้ในการฉายภาพแบบเมอร์เคเตอร์ รูปหลายเหลี่ยมที่ไม่ใช่จีโอเดสิกจะคงลักษณะที่ปรากฏเริ่มต้นบนหน้าจอไว้เสมอ
ในเส้นประกอบแบบจีโอเดสิก ส่วนต่างๆ ของเส้นประกอบจะวาดเป็นเส้นทางที่สั้นที่สุดระหว่างจุด 2 จุดบนพื้นผิวโลก โดยสมมติว่าโลกเป็นทรงกลม ตรงข้ามกับเส้นตรงบนการฉายภาพแบบเมอร์เคเตอร์
ดูข้อมูลเพิ่มเติมเกี่ยวกับระบบพิกัดได้ที่คู่มือพิกัดแผนที่และแผนที่ย่อย
แผนที่ต่อไปนี้แสดงสามเหลี่ยม 2 รูปที่มีขนาดและมิติข้อมูลใกล้เคียงกัน สามเหลี่ยมสีแดงมีพร็อพเพอร์ตี้ geodesic ที่ตั้งค่าเป็น true สังเกตว่ารูปร่างของพายุเปลี่ยนไปอย่างไรเมื่อเคลื่อนตัวไปทางเหนือ
ฟังเหตุการณ์การแก้ไข
เมื่อมีการแก้ไขรูปร่าง ระบบจะเริ่มเหตุการณ์เมื่อการแก้ไขเสร็จสมบูรณ์ เหตุการณ์เหล่านี้แสดงอยู่ด้านล่าง
| รูปร่าง | กิจกรรม |
|---|---|
| วงกลม |
radius_changedcenter_changed
|
| รูปหลายเหลี่ยม |
insert_atremove_atset_at
ต้องตั้งค่า Listener ในเส้นทางของรูปหลายเหลี่ยม หากรูปหลายเหลี่ยมมีหลายเส้นทาง คุณต้องตั้งค่า Listener ในแต่ละเส้นทาง |
| เส้นประกอบ |
insert_atremove_atset_at
ต้องตั้งค่า Listener ในเส้นทางของเส้นประกอบ |
| สี่เหลี่ยมผืนผ้า | bounds_changed |
ข้อมูลโค้ดที่เป็นประโยชน์บางส่วนมีดังนี้
google.maps.event.addListener(circle, 'radius_changed', function() { console.log(circle.getRadius()); }); google.maps.event.addListener(outerPath, 'set_at', function() { console.log('Vertex moved on outer path.'); }); google.maps.event.addListener(innerPath, 'insert_at', function() { console.log('Vertex removed from inner path.'); }); google.maps.event.addListener(rectangle, 'bounds_changed', function() { console.log('Bounds changed.'); });
ดูตัวอย่างการจัดการเหตุการณ์การแก้ไขในสี่เหลี่ยมผืนผ้า: ดูตัวอย่าง
ฟังเหตุการณ์การลาก
เมื่อลากรูปร่าง ระบบจะเริ่มเหตุการณ์เมื่อเริ่มและสิ้นสุดการลาก รวมถึงระหว่างการลากด้วย ระบบจะเริ่มเหตุการณ์ต่อไปนี้สำหรับเส้นประกอบ รูปหลายเหลี่ยม วงกลม และสี่เหลี่ยมผืนผ้า
| กิจกรรม | คำอธิบาย |
|---|---|
dragstart |
เริ่มทำงานเมื่อผู้ใช้เริ่มลากรูปร่าง |
drag |
เริ่มทำงานซ้ำๆ ขณะที่ผู้ใช้ลากรูปร่าง |
dragend |
เริ่มทำงานเมื่อผู้ใช้หยุดลากรูปร่าง |
ดูข้อมูลเพิ่มเติมเกี่ยวกับการจัดการเหตุการณ์ได้ที่เอกสารประกอบเกี่ยวกับเหตุการณ์
เขตพื้นที่เสมือนและขอบเขตโซนปลอดภัย
Google Maps Platform ไม่มี Geofencing API แบบสแตนด์อโลน หากต้องการแสดงรัศมีเขตพื้นที่เสมือนหรือโซนปลอดภัยบนแผนที่เว็บและตรวจสอบว่าพิกัดแบบเรียลไทม์อยู่ภายในขอบเขตนั้นหรือไม่ ให้รวมรูปร่างเข้ากับไลบรารีเรขาคณิต (google.maps.GeometryLibrary) ที่โหลดผ่าน google.maps.importLibrary("geometry") ดังนี้
- เขตพื้นที่เสมือนแบบวงกลม: วาด
google.maps.Circle(หรือส่งgoogle.maps.CircleLiteral) และทดสอบว่าพิกัดอยู่ภายในวงกลมหรือไม่โดยใช้google.maps.geometry.poly.containsLocation()หากต้องการระยะทางเป็นเมตรจากCircle.getCenter()ด้วย ให้เรียกใช้google.maps.geometry.spherical.computeDistanceBetween() - เขตพื้นที่เสมือนรูปหลายเหลี่ยม: วาด
google.maps.Polygonและทดสอบว่าพิกัดอยู่ภายในรูปหลายเหลี่ยมหรือไม่โดยใช้google.maps.geometry.poly.containsLocation() - รูปหลายเหลี่ยมในแผนที่ 3 มิติ: ในแผนที่ 3 มิติ (รูปร่างและเส้น) ให้วาด
google.maps.maps3d.Polygon3DElementและส่งพิกัดPolygon3DElement.pathไปยังgoogle.maps.Polygonเมื่อเรียกใช้google.maps.geometry.poly.containsLocation()
ตัวอย่างต่อไปนี้จะวาดโซนที่ปลอดภัยแบบวงกลมและเขตพื้นที่เสมือนแบบรูปหลายเหลี่ยม จากนั้นจะตรวจสอบว่าพิกัดแบบเรียลไทม์อยู่ภายในขอบเขตแต่ละขอบเขตหรือไม่
const {Circle, Polygon} = await google.maps.importLibrary("maps"); const {poly} = await google.maps.importLibrary("geometry"); const livePosition = {lat: 37.424, lng: -122.085}; // 1. Circular geofence (500-meter radius) const circularGeofence = new Circle({ map, center: {lat: 37.422, lng: -122.084}, radius: 500, }); const isInsideCircle = poly.containsLocation(livePosition, circularGeofence); // 2. Polygonal geofence const polygonGeofence = new Polygon({ map, paths: [ {lat: 37.420, lng: -122.088}, {lat: 37.420, lng: -122.080}, {lat: 37.426, lng: -122.080}, {lat: 37.426, lng: -122.088}, ], }); const isInsidePolygon = poly.containsLocation(livePosition, polygonGeofence);