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:If 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

Tips for generating a JSON string with nested structure

Can someone assist me in generating a JSON based on the HTML elements provided below? { "AppName": "ERP", "ModuleDesc": [ { "Name": "Payroll", "AcCESSRIGHTS": [ { "Create": "Y", "Retrive": "Y", "U ...

Testing the speed of the client's side

In my quest to create an application that allows users to conduct a speedtest on their WiFi network, I have encountered some challenges. While standalone speedtest apps like Speedtest.net and Google exist, server-based speed test modules from NPM are not s ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

What could be the reason for the malfunctioning toggle button on the Bootstrap navbar?

I'm having trouble with my bootstrap navbar. I've added the .sidebar-collapse class to the body tag so that when I click on the toggle button, the data should appear on the right side. However, this isn't happening. Can anyone spot what&apos ...

Creating a custom comparison method between two select dropdowns using the jQuery Validation plugin

In my HTML code, I have two select elements: <label for="h_slat_type">Horizontal Slat Type</label> <select name="h_slat_type" id="h_slat_type"> <option disabled="disabled" selected>Select</option> ...

Positioning CSS for a Responsive Button

Currently, I am working on making my modal responsive. However, I am encountering an issue with the positioning of the "SAVE" button. The button is not staying in the desired position but instead disappears. Below is the snippet of my HTML and CSS: .dele ...

`My jquery mobile application fails to trigger the pageinit or ready events`

My website consists of 3 PHP pages: one index page and two subpages for sales and products. The index page has links to these subpages. When I click on the sales link, it is supposed to load sales data either on pageinit or document ready. However, no code ...

Styled-components does not generate a style tag as output

After creating a new project in React with Webpack, I decided to experiment with Styled Components. In my index.js file, the code is structured like this: import React from "react" import ReactDOM from "react-dom" import Page from "./site/Page" import s ...

Update DataTable 1.9 while preserving existing rows

I'm currently using dataTables js version 1.9 Periodically, an ajax call is made to the server to retrieve information that should be displayed in a table every 60 seconds or so. Although I can easily clear and repopulate the table like this: $(id) ...

Rest parameter ...args is not supported by Heroku platform

When interacting with Heroku, an error message SyntaxError: Unexpected token ... appears. What modifications should be made to this function for compatibility with Heroku? authenticate(...args) { var authRequest = {}; authRequest[ ...

Customizing the tab content background color in MaterializeCSS

I've been struggling to customize the background color of my MaterializeCSS tabs content by referring to their official documentation: If you visit the website, you'll notice that the default tabs have a white background, while the 'Test 1& ...

How to position preloader at the center in materializeCSS

Given this situation: I attempted to implement this Preloader with position:fixed and centered. My approach was as follows: .loader { position:fixed; top:50%; left:50%; -webkit-transform:translate(-50%,-50%); } <link rel="stylesheet" href="h ...

Guide on transmitting information from two separate pages to a PHP script simultaneously using an AJAX request

Looking to gather user information from a form and pass it onto another page smoothly. Origin Site <form action="destination.php" method="post"> Name: <input type="text" name="name"> Email: <input type="text" name="email"> <input typ ...

Is it possible to set up an automatic redirection to the Identity Provider sign-in page when accessing a protected page in Next.js using Auth.js?

Currently in the process of developing a web platform utilizing [email protected] and Auth.js([email protected]). The provider has been configured with the given code, allowing successful signing in using the "Sign in" button. auth.ts import Ne ...

The development server fails to respond when initializing a new project following the NextJs documentation for an empty project

After consulting the NextJs framework documentation, I meticulously followed the setup instructions to initialize an empty project : mkdir hello-next cd hello-next npm init -y npm install --save react react-dom next mkdir pages Subsequently, I included t ...

How to effectively leverage useMediaQuery in material ui?

Upon completing the web application, I have made the decision to ensure it is mobile-friendly. Utilizing the material UI framework with react, I delved into the documentation but found myself uncertain about how to effectively implement it. Let me provide ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

How can I modify the content within a scoped `<style>` tag in Vue?

Is there a way to dynamically change the contents of a <style> block in my Vue component using Vue variables? Many commonly suggested solutions involve inline styles or accessing the .style property with JavaScript. However, I am looking for a metho ...

CSS 3 - Apply transition to the 'display' property

I have a question about using the transition effect in conjunction with the display property: Currently, I am testing on Safari. input.input_field { display:none; transition-property: display; transition-duration: 2s; -webkit-transition-p ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...