I'm currently working on a project that involves drawing and editing polygons on a Google Map using the Google Maps JavaScript API. I've implemented functionality to allow users to edit existing polygons and save their changes. However, I'm encountering an issue where the edited polygon is not showing up after saving the changes, while a newly created polygon does.
Problem Description:
Users can select a city from a dropdown menu, which then displays an existing polygon on the map representing the delivery area for that city. Users can edit the existing polygon (e.g., adjusting boundaries) using the editing tools provided by the Google Maps API. After making edits, users can save their changes by clicking a "Save Boundaries" button. Upon saving, the expected behavior is to update the existing polygon on the map with the edited boundaries. However, while the saved changes are registered (confirmed by alerting the vertices variable), the edited polygon is not displayed on the map. Instead, a new polygon is created with the original boundaries.
<script>
var map;
var cityPolygon;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: { lat: 40.712776, lng: -74.005974 }, // Default to New York City
zoom: 10
});
}
function drawCityPolygon(polygonCoords) {
// if (cityPolygon && cityPolygon.setMap) cityPolygon.setMap(null);
cityPolygon = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
editable: true , // Enable editing
logo: true
});
cityPolygon.setMap(map);
}
function clearMap() {
if (cityPolygon && cityPolygon.setMap) {
cityPolygon.setMap(null);
}
}
$('#city_id').on("change", function() {
// Clear the map before drawing the new polygon
clearMap();
// Draw the polygon for the selected city
var selectedCity = $(this).val();
var selectedOption = this.options[this.selectedIndex];
var boundaryPoints = selectedOption.getAttribute("data-boundary_points");
console.log("selected boundaryPoints >>>> " + boundaryPoints);
if (selectedCity) {
// Split the selectedCity value to get latitude and longitude
var coordinates = selectedCity.split(',');
var latitude = parseFloat(coordinates[0]);
var longitude = parseFloat(coordinates[1]);
// Center the map on the selected city
map.setCenter({ lat: latitude, lng: longitude });
}
if (boundaryPoints) {
var polygonCoords = JSON.parse(boundaryPoints);
drawCityPolygon(polygonCoords);
}
});
$("#save_city").on("click", function (event) {
event.preventDefault();
var city_id = $("#city_id").find(":selected").data("city_id");
var vertices = $("#vertices").val();
alert(vertices);
var final_array = [];
var geolocation_type = "";
var radius = "";
if (vertices && city_id) {
if (isJSON(vertices) === true) {
geolocation_type = "circle";
var parse_json = JSON.parse(vertices);
$.each(parse_json, function (index, item) {
radius = item.radius;
final_array.push({
lat: parseFloat(item.lat),
lng: parseFloat(item.long)
});
});
} else {
geolocation_type = "polygon";
radius = "";
var str1 = vertices.split("),");
$.each(str1, function (index, item) {
var str2 = item.replace("(", "");
var str3 = str2.replace(")", "");
final_array.push({
lat: parseFloat(str3.split(",")[0]),
lng: parseFloat(str3.split(",")[1])
});
});
}
$('input[name="city_outlines"]').val(JSON.stringify(final_array));
Swal.fire({
title: "Are You Sure !",
text: "You won't be able to revert this!",
type: "info",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, Update it!",
showLoaderOnConfirm: true,
preConfirm: function () {
return new Promise((resolve, reject) => {
$.ajax({
url: base_url + from + "/area/add_city",
type: "POST",
data: {
boundary_points: $('input[name="city_outlines"]').val(),
edit_city: city_id,
radius: radius,
geolocation_type: geolocation_type,
[csrfName]: csrfHash
},
dataType: "json"
})
.done(function (response, textStatus) {
csrfName = response["csrfName"];
csrfHash = response["csrfHash"];
if (response.error == false) {
Swal.fire("Done!", response.message, "success");
$("#vertices").val("");
location.reload();
} else {
Swal.fire("Oops...", response.message, "warning");
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
Swal.fire("Oops...", "Something went wrong with ajax !", "error");
});
});
},
allowOutsideClick: false
});
} else {
iziToast.error({
message:
'<span style="text-transform:capitalize">Please, Select city or its outlines!</span> '
});
}
});
function fetchPolygonCoords(cityName) {
// Clear the map before fetching new polygon coordinates
clearMap();
// Make an AJAX request to fetch polygon coordinates for the selected city
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var cityPolygons = JSON.parse(xhr.responseText);
drawCityPolygon(cityPolygons[cityName]);
} else {
console.error('Failed to fetch polygon coordinates:', xhr.status);
}
}
};
// Adjust the URL to match your server endpoint for fetching polygon coordinates
xhr.open('GET', 'https://order.my1922.com/admin/area/polygon_data?city=' + encodeURIComponent(cityName), true);
xhr.send();
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?= $google_map_api_my_apkey ?>&libraries=drawing&v=weekly"></script>
The issue seems to be related to updating the existing polygon rather than creating a new one. I've verified that the correct polygon coordinates are being saved and sent to the server. The issue occurs consistently across different browsers and devices. I'm using the latest version of the Google Maps JavaScript API (v3). I've checked the server-side code, and it appears to be functioning correctly, updating the polygon coordinates in the database upon receiving the request.
Any insights or suggestions on what might be causing the edited polygon not to display after saving the changes would be greatly appreciated. Thank you!