Manipulate the lines in an HTML map and showcase the distinctions between them

I've been searching through various inquiries on this particular subject, but none have provided me with a satisfactory response. I have created a map where I've set up 4 axes using the following code:

function axis() {
        var bounds = map.getBounds();
        var NECorner = bounds.getNorthEast();
        var SWCorner = bounds.getSouthWest();

        // horizontal top axis

        var PolylineCoordinates = [
            new google.maps.LatLng(NECorner.lat()-0.0002, NECorner.lng()),
            new google.maps.LatLng(NECorner.lat()-0.0002, SWCorner.lng()),
        ];

        var Path = new google.maps.Polyline({
            clickable: false,
            geodesic: true,
            path: PolylineCoordinates,
            strokeColor: "#FF0000",
            strokeOpacity: 1.000000,
            strokeWeight: 0.8
        });

        Path.setMap(map);

        // horizontal low axis

        var PolylineCoordinates = [
            new google.maps.LatLng(SWCorner.lat()+0.0002, NECorner.lng()),
            new google.maps.LatLng(SWCorner.lat()+0.0002, SWCorner.lng()),
        ];

        var Path = new google.maps.Polyline({
            clickable: false,
            geodesic: true,
            path: PolylineCoordinates,
            strokeColor: "#FF0000",
            strokeOpacity: 1.000000,
            strokeWeight: 0.8
        });

        Path.setMap(map);

        // vertical left axis

        var PolylineCoordinates...
    
    

Now, my objective is to be able to drag these axes horizontally or vertically (depending on the axis) and continuously monitor the position difference between them - both in terms of the horizontals and verticals.

The visual output can be viewed here:https://i.sstatic.net/oadAv.pngIf the question remains unclear, my requirements are as follows:

- ability to move/adjust the four red lines by dragging them with the mouse

- display the value of: abs(latitude_axis1 - latitude-axis2) and abs(longitude_axis1 - longitude-axis2) above the map

If anyone has knowledge or solutions regarding this issue, please assist me. If not, do you know of any similar queries that have been resolved? Thank you.

Answer №1

My code lacks user-friendly features, such as preventing the user from dragging the north line under the south line or allowing the lines to be dragged too far...

However, this fulfills your request to some extent.

Remember to update your API key

UPDATE: In line 46, you can change 'dragend' to 'drag'. This will alter the display while the user is dragging

<!DOCTYPE html>
<html>
<head>
    <title>Drag Lines in HTML Map and Display Line Differences</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        #map {
            height: 90%;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <div id="log"></div>
    <div id="info">
        <a href="http://stackoverflow.com/questions/39370766/drag-lines-in-html-map-and-display-difference-between-lines/39376480#39376480">Stackoverflow</a>
    </div>
    <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
    <script>
        var map;
        var initialViewportCoordinates = {
          north: 51.0,
          east:  5.0,
          south: 50.0,
          west: 3.0
        };
        var extraDegrees = 10;  
        var lineObjects = [];

        function drawPolyline(path, color) {
            var line = new google.maps.Polyline({
                path: path,
                draggable: true,
                strokeColor: color,
                strokeOpacity: 0.9,
                strokeWeight: 3
            });
            line.setMap(map);
            
            google.maps.event.addDomListener(line, 'dragend', function(e) {
              var index = lineObjects.indexOf(this);
              
              switch(index) {
                case 0: initialViewportCoordinates.north = e.latLng.lat(); break;
                case 1: initialViewportCoordinates.east =  e.latLng.lng(); break;
                case 2: initialViewportCoordinates.south = e.latLng.lat(); break;
                case 3: initialViewportCoordinates.west =  e.latLng.lng(); break;
              }
              displayDifference();
            });
            return line;
        }
        
        function displayDifference() {
          document.getElementById('log').innerHTML = 
            'difference lat: ' + (initialViewportCoordinates.north - initialViewportCoordinates.south) + '<br/>' +
            'difference lng: ' + (initialViewportCoordinates.east - initialViewportCoordinates.west) ;
        }
        
        function drawViewport() {
          var north = [
            {lat: initialViewportCoordinates.north , lng: initialViewportCoordinates.east + extraDegrees},
            {lat: initialViewportCoordinates.north, lng: initialViewportCoordinates.west - extraDegrees}
          ];
          var east = [
            {lat: initialViewportCoordinates.north + extraDegrees , lng: initialViewportCoordinates.east},
            {lat: initialViewportCoordinates.south - extraDegrees, lng: initialViewportCoordinates.east}
          ];
          var south = [
            {lat: initialViewportCoordinates.south , lng: initialViewportCoordinates.east + extraDegrees},
            {lat: initialViewportCoordinates.south, lng: initialViewportCoordinates.west - extraDegrees}
          ];
          var west = [
            {lat: initialViewportCoordinates.north + extraDegrees , lng: initialViewportCoordinates.west},
            {lat: initialViewportCoordinates.south - extraDegrees, lng: initialViewportCoordinates.west}
          ];

          lineObjects = [
            drawPolyline(north, '#ff0000'),
            drawPolyline(east, '#ff0000'),
            drawPolyline(south, '#ff0000'),
            drawPolyline(west, '#ff0000')
          ];
        }

        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: 50.84, lng: 4.35},
                zoom: 7,
                mapTypeId: 'terrain'
            });

            drawViewport();
            displayDifference();
        }
        
        google.maps.event.addDomListener(window, 'load', initMap);
    </script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to implement Redux login to display the first letter of a user's name and their login name simultaneously

I am implementing a Redux login feature and after successful login, I want to display the first letter of the user's name or email in a span element within the header section. Can anyone provide a solution for this? Below is my Redux login code snippe ...

Utilizing MongoDB query for geoLocation with maxDistance parameter

Customer location: customerCoordinates: [83,24] stores: { id:1, location: {coordinates:[85,44]...} maxRadiusDelivery: 2000 //meters }, { id:2, location: {coordinates:[82,34]...} maxRadiusDelivery: 100 //meters } Query: db.wh.find({ 'locati ...

The data retrieved by jQuery AJAX is empty when accessed outside of the success handler

Here is a code snippet to consider: let source = null; fetch('https://example.com/data') .then(response => response.json()) .then(data => { source = data; console.log(source); }); console.log(source) When the fetch request ...

Using the jquery slider in conjunction with the onchange event

I have integrated a jquery slider add-on into my project that updates a value in a Linux file whenever it is manipulated. The slider is connected to a text input box, which is set as readonly and therefore always blurred. The issue I am facing is that the ...

Activate an asynchronous request within a dropdown menu that was loaded using ajax

Let me start by presenting a simplified version of my code: HTML : <form id="add"> <select id="cat"> <option selected value="">…</option> <option value="a">A</option> <option value="b"& ...

The error of "No 'Access-Control-Allow-Origin' header is present on the requested resource" persists even after implementing the Access-Control-Allow-Origin header

I'm trying to retrieve JSON data from a Firebase cloud function. The JSON URL works fine on the browser and my Android app, but I encounter issues when trying to fetch it in my JavaScript code. This results in an error message: No 'Access-Cont ...

Retrieving a specific variable from a cookie value that is stored within a JSON array

Is there a way to pass a single variable from a JSON array stored in the qookie file value to JavaScript? The qookie code looks like this: <?php $cookie_key = 'count'; CookieManager::store($cookie_key, json_encode(array( 'SameSite&ap ...

What is the best way to trigger a refresh in Next.js React component?

Current Tech Stack Versions Next.js : 14.0.3 React : 18.0.2 // TestClientComponent.tsx "use client"; import { IResident } from "@interface/resident.types"; import { getResidents } from "@models/resident.service"; import { So ...

Unique WordPress Loop Design (Grid/Row)

Looking for a custom Wordpress post loop that will display posts in a specific format. The desired layout includes two posts in each "col" div, both contained within a "row" div: <div class="row cols2"> <div class="col left"> <a href="#"> ...

Why is it that my jquery code seems to be struggling with calculating the count accurately?

I'm currently working on restricting keyword input on my website. My goal is to automatically add a 'span' tag to any keyword entered by a user, as shown in the example html code below. Although I can limit the number of words, the count i ...

The Backbone Model is producing unspecified data

Having crafted a backbone model, it looks like this: var note_model = Backbone.Model.extend({ default : { HistoryKey : "", InsertDate : "", MemberKey : "", NoteDate : "", ContactNote : "", User ...

Error: The function getOrders is not defined in the customerFactory

Throughout my third attempt at learning AngularJS, I've hit a roadblock. I could really use some assistance as I keep encountering the error TypeError: customerFactory.getOrders is not a function. Despite thoroughly checking for typos, I haven't ...

Changing the application's state from within a child component using React and Flux

UPDATE It seems that my initial approach was completely off base. According to the accepted answer, a good starting point is the TodoMVC app built with React + Flux and available on GitHub. I am currently working on a small React + Flux application for ed ...

Trouble displaying CSS content image in Internet Explorer

Usually, I use Chrome as my default browser. However, I recently decided to test whether my website functions properly on other browsers as well. In Chrome, the header displays my logo with great quality using content:url. But when I tried accessing my w ...

How should we arrange these components to optimize the overall aesthetic of this particular design?

My current progress on the code: Visit this link Desired design for reference: View design picture here I've experimented with position relative and margins, but these techniques have impacted the responsiveness of my webpage. What is the most eff ...

Loop through the array and eliminate the identification solely

{ "productGroupVariantss": [ { "id": 1378, "name": "No oF Poles", "variantsAttributeses": [ { "id": 391, "variantsId": null, "variantsValue": "1p" }, { "id": 392, ...

While iterating through a dynamically generated JSON data array, omitting the display of the ID (both title and value) is preferred

I am working with a JSON data Object and using $.each to dynamically retrieve the data. However, I want to display all values except for one which is the ID. How can I achieve this and prevent the ID from being displayed in the HTML structure? Thank you. ...

jQuery functions smoothly on Firefox, but encountering issues on Chrome

While it may seem like a repetitive inquiry, I have thoroughly researched similar questions and have not found a suitable solution. The server is returning the following response through a standard ajax call: <form id="ctl00" name="ctl00" method="post ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

Transforming images with Imagick

I've been trying to generate thumbnails from PDF uploads using Imagick. I have a script that is supposed to handle this task, but unfortunately, it only uploads the file without creating a thumbnail. I know some of you may find this basic, but PHP is ...