0

I want to save my coordinates from the frontend to the backend and I don't know how to send them. the coordinates are saved in a JS array and I don't know how to transfer them to C#.

HTML, CSS & JS for the map

<link rel="stylesheet" href="~/css/ol.css">
        <link rel="stylesheet" href="~/css/ol-ext.css">


        <script src="~/js/ol.js"></script>

        <script src="~/js/ol-ext.js"></script>

        @*<script src="~/js/elm-pep"></script>*@

        @*<script src="~/js/JavaScript.js"></script>*@



        <div id="map" style="width:600px; height:400px;">
            <div class="photon ol-search ol-unselectable ol-control ol-collapsed">
                <input asp-for="coordinates" type="search" class="search" autocomplete="off" placeholder="Search...">
                <input asp-for="coordinates" type="button" class="ol-revers" title="click on the map">
                <ul class="autocomplete history">
                    <li data-search="0"> 398<i> 9350004 Jérusalem (Israël)</i></li>
                    <li class="copy"><a href="http://www.openstreetmap.org/copyright" target="new">© OpenStreetMap contributors</a></li>
                </ul>
            </div>
        </div>


        <div class="button-70" style="z-index:1;" id="location-button">
            @*<button id="location-button" title="Get your location"></button>*@
            @*<button asp-for="coordinates" class="button-70" id="location-button" role="button" title="Get your current location"> Get cuttent location</button>*@
            <input asp-for="coordinates" type="button" value=" Get cuttent location" id="location-button" />
        </div>


        <style>
            .button-70 #location-button {
                background: none;
                border: none;
                transform: scale(2)
            }

            .button-70 {
                transform: scale(0.7);
                background-image: linear-gradient(#0dccea, #0d70ea);
                border: 0;
                border-radius: 4px;
                box-shadow: rgba(0, 0, 0, .3) 0 5px 15px;
                box-sizing: border-box;
                color: #fff;
                cursor: pointer;
                font-family: Montserrat,sans-serif;
                font-size: .9em;
                margin: 5px;
                padding: 10px 15px;
                text-align: center;
                user-select: none;
                -webkit-user-select: none;
                touch-action: manipulation;
            }
        </style>

        <script type="text/javascript">

            var layers = [new ol.layer.Tile({ source: new ol.source.OSM() })];

            var map = new ol.Map({
                target: 'map',
                view: new ol.View({
                    zoom: 5,
                    center: [166326, 5992663]
                }),
                interactions: ol.interaction.defaults({ altShiftDragRotate: false, pinchRotate: false }),
                layers: layers
            });

            var search = new ol.control.SearchPhoton({
                lang: "fr",
                reverse: true,
                position: true
            });
            map.addControl(search);

            var markers;
            search.on('select', function (e) {

                map.getView().animate({
                    center: e.coordinate,
                    zoom: Math.max(map.getView().getZoom(), 16)
                });

                loc(e.coordinate);
            });

            function loc(e) {
                console.log(e);
                if (markers) {
                    map.removeLayer(markers)
                }

                markers = new ol.layer.Vector({
                    source: new ol.source.Vector(),
                    style: new ol.style.Style({
                        image: new ol.style.Icon({
                            anchor: [0.5, 1],
                            src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
                        })
                    })
                });

                map.addLayer(markers);

                var marker = new ol.Feature(new ol.geom.Point(e));
                markers.getSource().addFeature(marker);

            }

            const options = {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
            };

            document.querySelector("#location-button").addEventListener("click", function (e) {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function (position) {
                        console.log(e);
                        if (markers) {
                            map.removeLayer(markers)
                        }

                        markers = new ol.layer.Vector({
                            source: new ol.source.Vector(),
                            style: new ol.style.Style({
                                image: new ol.style.Icon({
                                    anchor: [0.5, 1],
                                    src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
                                })
                            })
                        });

                        map.addLayer(markers);

                        function success(pos) {
                            const crd = pos.coords;

                            console.log('Your current position is:');
                            console.log(`Latitude : ${crd.latitude}`);
                            console.log(`Longitude: ${crd.longitude}`);
                            console.log(`More or less ${crd.accuracy} meters.`);
                            return new Array(crd.latitude, crd.longitude);
                        }

                        function error(err) {
                            console.warn(`ERROR(${err.code}): ${err.message}`);
                        }

                        navigator.geolocation.getCurrentPosition(success, error, options);

                        var marker = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([position.coords.latitude, position.coords.longitude])));
                        markers.getSource().addFeature(marker);
                    });
                }
                else {
                    alert("Your browser does not support geolocation");
                }
            });
        </script>

I tried to save the coordinates in A list and in a string, but none worked. here is the Model code:

public class ReportModel
{
    //...stuff...
    public string coordinates { get; set; }
    //...more stuff...
}

ReportDAO.cs - Saves the given data form the user

using Microsoft.Data.SqlClient;
using SvivaTeamVersion3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SvivaTeamVersion3.Services
{
    public class ReportDAO
    {
        static readonly string connectionString = @"KEY";
        public static bool addReport(ReportModel report)
        {
            bool success = false;
            string sqlStatement = "INSERT INTO dbo.Reports (category,title,description,statUrgence,cordsLat,cordsLong) VALUES (@category,@title,@description,@statUrgence,@cordsLat,@cordsLong)";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(sqlStatement, connection);

                command.Parameters.Add("@category", System.Data.SqlDbType.NChar, 32).Value = report.category;
                command.Parameters.Add("@title", System.Data.SqlDbType.NChar, 32).Value = report.title;
                command.Parameters.Add("@description", System.Data.SqlDbType.NVarChar, -1).Value = report.remarks;
                command.Parameters.Add("@statUrgence", System.Data.SqlDbType.NVarChar, -1).Value = report.statUrgence;
                command.Parameters.Add("@cordsLat", System.Data.SqlDbType.Float).Value = report.coordinates;
                command.Parameters.Add("@cordsLong", System.Data.SqlDbType.Float).Value = 0;
                //I've tried to merge the lat and long to a single string, didn't work.
                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                    success = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                return success;

            }
        }
    }
}
  • You need to send them in a json string format, you need to serialize and deserialize the json string. You could deserialize the json manually here: https://json2csharp.com/ and copy paste the classes – BR75 Aug 14 '22 at 10:28
  • How do I send them in a json string format? –  Aug 14 '22 at 10:56
  • Post request, how do you communicate with your server? – BR75 Aug 14 '22 at 11:07
  • If I understood you correctly then I have an SQL server. On the same page, I have a button "Add Report" when I click on it activates the Controller, the controller call's a DAO (reportDAO.cs) class there I have a function that takes a given ReportModel and uploads it to the server. I'll add the DAO code rn. –  Aug 14 '22 at 11:16
  • Never heard of reportdao it seems that you first need to learn the basics of server client communication – BR75 Aug 14 '22 at 12:21
  • Does it really matter? I just want to save the coordinates into a variable. –  Aug 15 '22 at 18:45
  • So your problem is not about how you can send your data to the server but why you can’t save the coordinates into the database? Do you have any error messages? – BR75 Aug 15 '22 at 20:05
  • My problem is to get it from the site to the Model class. Even before I send it to the DB. –  Aug 15 '22 at 20:50
  • Like I said, post request. – BR75 Aug 16 '22 at 19:31
  • what do you mean by a request –  Aug 16 '22 at 20:23
  • I saw a video that explains what it is but I don't have a URL right now so how exactly I do this? –  Aug 16 '22 at 20:36
  • You need to communicate to your server in the backend that you like to save somehting into the database, to to that you need a api in your backend like rest-api. So in you backend you would have a method like "saveCoordinates" you call this method (from client side) with a post request. In the request body you would pass the parameters like your coordinates. https://stackoverflow.com/questions/14551194/how-are-parameters-sent-in-an-http-post-request – BR75 Aug 17 '22 at 07:22
  • How can I see the new link that I get back? when I press the send button the link doesn't change, after clicking it stays https://localhost:PORT/.../ and not change to https://localhost:PORT/.../values –  Aug 19 '22 at 20:29

0 Answers0