Can anyone please suggest how to draw polygon in the map

Can anyone please suggest how to draw polygon in the map. It would be helpful if you provide example with script

1 Like

hi @sheetalgoudarsb

here are several approaches depending on the type of map implementation:

Approach 1: Using JavaScript Execution for Google Maps

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import com.kms.katalon.core.webui.driver.DriverFactory
import org.openqa.selenium.WebDriver
import org.openqa.selenium.JavascriptExecutor

// Navigate to your map page
WebUI.openBrowser('https://your-map-application.com')
WebUI.maximizeWindow()

// Wait for map to load
WebUI.waitForElementPresent(findTestObject('Page_Map/div_mapContainer'), 10)

// Get the driver for JavaScript execution
WebDriver driver = DriverFactory.getWebDriver()
JavascriptExecutor js = (JavascriptExecutor) driver

// Define polygon coordinates (latitude, longitude pairs)
String polygonScript = '''
    // Assuming 'map' is the global map variable
    var polygonCoords = [
        {lat: 37.772, lng: -122.214},
        {lat: 37.771, lng: -122.213},
        {lat: 37.770, lng: -122.215},
        {lat: 37.769, lng: -122.216},
        {lat: 37.772, lng: -122.214}  // Close the polygon
    ];
    
    // Create the polygon
    var polygon = new google.maps.Polygon({
        paths: polygonCoords,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });
    
    // Add polygon to map
    polygon.setMap(map);
    
    return "Polygon drawn successfully";
'''

// Execute the script
String result = js.executeScript(polygonScript)
println("Result: " + result)

// Verify polygon is visible (optional)
WebUI.delay(2)
WebUI.takeScreenshot()

Approach 2: Drawing Polygon by Clicking Points on Map

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import org.openqa.selenium.interactions.Actions
import com.kms.katalon.core.webui.driver.DriverFactory
import org.openqa.selenium.WebElement

// Navigate to map
WebUI.openBrowser('https://your-map-application.com')
WebUI.maximizeWindow()

// Wait for map and drawing tools
WebUI.waitForElementPresent(findTestObject('Page_Map/div_mapCanvas'), 10)

// Click on polygon drawing tool (adjust selector as needed)
WebUI.click(findTestObject('Page_Map/btn_drawPolygon'))

// Define points for polygon (x, y coordinates relative to map element)
def polygonPoints = [
    [x: 200, y: 150],
    [x: 350, y: 180],
    [x: 400, y: 300],
    [x: 250, y: 350],
    [x: 150, y: 250]
]

// Get map element
WebElement mapElement = WebUI.findWebElement(findTestObject('Page_Map/div_mapCanvas'))

// Create Actions instance
Actions actions = new Actions(DriverFactory.getWebDriver())

// Click each point to draw polygon
polygonPoints.each { point ->
    actions.moveToElement(mapElement, point.x, point.y)
           .click()
           .build()
           .perform()
    WebUI.delay(1)  // Small delay between clicks
}

// Double-click or click first point again to close polygon
actions.moveToElement(mapElement, polygonPoints[0].x, polygonPoints[0].y)
       .doubleClick()
       .build()
       .perform()

// Verify polygon creation
WebUI.verifyElementPresent(findTestObject('Page_Map/svg_polygon'), 5)

Approach 3: Using Custom Keywords for Reusability

// CustomKeywords.groovy
package com.example

import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.webui.driver.DriverFactory
import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.WebDriver

public class MapDrawing {
    
    @Keyword
    def drawPolygonOnMap(List<Map> coordinates, String mapVariableName = 'map') {
        WebDriver driver = DriverFactory.getWebDriver()
        JavascriptExecutor js = (JavascriptExecutor) driver
        
        // Convert coordinates to JavaScript array format
        String coordsArray = coordinates.collect { 
            "{lat: ${it.lat}, lng: ${it.lng}}" 
        }.join(',')
        
        String script = """
            var polygonCoords = [${coordsArray}];
            
            var polygon = new google.maps.Polygon({
                paths: polygonCoords,
                strokeColor: '#0000FF',
                strokeOpacity: 0.8,
                strokeWeight: 3,
                fillColor: '#0000FF',
                fillOpacity: 0.35,
                editable: true,
                draggable: true
            });
            
            polygon.setMap(${mapVariableName});
            
            // Store polygon reference for later use
            window.lastDrawnPolygon = polygon;
            
            return polygon.getPath().getLength();
        """
        
        return js.executeScript(script)
    }
    
    @Keyword
    def drawPolygonByClicks(List<Map> points, int delayBetweenClicks = 500) {
        import org.openqa.selenium.interactions.Actions
        import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
        
        Actions actions = new Actions(DriverFactory.getWebDriver())
        
        // Enable drawing mode
        WebUI.click(findTestObject('Map/btn_drawPolygon'))
        
        // Click each point
        points.each { point ->
            WebUI.click(findTestObject('Map/div_mapCanvas'), 
                       FailureHandling.CONTINUE_ON_FAILURE,
                       [x: point.x, y: point.y])
            Thread.sleep(delayBetweenClicks)
        }
        
        // Close polygon by clicking first point again
        if (points.size() > 0) {
            WebUI.click(findTestObject('Map/div_mapCanvas'),
                       FailureHandling.CONTINUE_ON_FAILURE,
                       [x: points[0].x, y: points[0].y])
        }
    }
}

// Usage in test case:
def coordinates = [
    [lat: 40.7128, lng: -74.0060],
    [lat: 40.7580, lng: -73.9855],
    [lat: 40.7489, lng: -73.9680],
    [lat: 40.7128, lng: -74.0060]
]

CustomKeywords.'com.example.MapDrawing.drawPolygonOnMap'(coordinates)

Approach 4: For Leaflet Maps

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import com.kms.katalon.core.webui.driver.DriverFactory
import org.openqa.selenium.JavascriptExecutor

WebUI.openBrowser('https://your-leaflet-map.com')

JavascriptExecutor js = (JavascriptExecutor) DriverFactory.getWebDriver()

String leafletScript = '''
    // For Leaflet maps
    var polygonPoints = [
        [51.509, -0.08],
        [51.503, -0.06],
        [51.51, -0.047],
        [51.509, -0.08]
    ];
    
    var polygon = L.polygon(polygonPoints, {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5
    }).addTo(map);
    
    // Optionally fit map to polygon bounds
    map.fitBounds(polygon.getBounds());
    
    return "Leaflet polygon drawn";
'''

js.executeScript(leafletScript)
3 Likes

@sheetalgoudarsb

What is “the map“ you mean?

Is it Google Map? or anything else?

You need to specify which Map service you want to play on, as every services will have their own specific API.

1 Like

Hi @sheetalgoudarsb,

Welcome to our community. Have you solved your issue yet?

If yes, feel free to share how you done. If no, please help provide more information so that we can better support.

Thank you