Tips on connecting multiple polylines to a draggable marker

I am facing an issue where I have multiple polylines and I want to bind them with draggable markers. However, when I attempt to bind the markers with the polylines, the markers disappear.

var locations = {
    "feed1": [
        [25.774252, -80.190262],
        [18.466465, -66.118292],
        [32.321384, -64.75737]
    ],
    "feed2": [
        [32.321384, -64.75737],
        [36.321384, -88.75737]
    ],
    "feed3": [
        [20.466465, -68.118292],
        [34.321384, -66.75737],
        [27.774252, -82.190262]
    ]
};

function MVCArrayBinder(mvcArray) {
    this.array_ = mvcArray;
}
MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function(key) {
    if (!isNaN(parseInt(key))) {
        return this.array_.getAt(parseInt(key));
    } else {
        this.array_.get(key);
    }
}
MVCArrayBinder.prototype.set = function(key, val) {
    if (!isNaN(parseInt(key))) {
        this.array_.setAt(parseInt(key), val);
    } else {
        this.array_.set(key, val);
    }
}

function marFunc(event) {
    console.log(event.latLng);
    var path = poly.getPath();

    path.push(event.latLng);
    var len = path.getLength();
    var marker = new google.maps.Marker({
        position: event.latLng,
        map: map,
        draggable: true
    });
    marker.bindTo('position', poly.binder);
}

var poly;
var map;

function initialize() {
    var polyOptions = {
        strokeColor: '#000000',
        strokeOpacity: 1.0,
        strokeWeight: 3,
        map: map
    };
    poly = new google.maps.Polyline(polyOptions);

    var bounds = new google.maps.LatLngBounds();
    map = new google.maps.Map(document.getElementById('map'), {
        center: new google.maps.LatLng(25.774252, -80.190262),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var markers = new Array();
    var polycoordinate = Array();

    poly.binder = new MVCArrayBinder(poly.getPath());
    for (var i in locations) {
        for (j in locations[i]) {
            var evt = {};
            evt.latLng = new google.maps.LatLng(locations[i][j][0], locations[i][j][1]);
            bounds.extend(evt.latLng);
            marFunc(evt);
        }
    }
    poly.setMap(map);
    map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);

Within the initialize() function, I iterate through the object to render the polylines and simultaneously pass the latitude and longitude to the marFunc() function to create markers.

This is the result I am currently experiencing: https://i.sstatic.net/DAADt.png

Answer №1

There seems to be a typo in your code where you forgot to include the last argument of the "bindTo" function:

marker.bindTo('position', poly.binder);

It should actually be:

marker.bindTo('position', poly.binder, (len-1).toString());

For a related question, you can check out: Google Maps V3 Polyline : make it editable without center point(s)

Here is a proof of concept fiddle and the https://i.sstatic.net/KpyqF.png

Code Snippet:

var locations = {
  "feed1": [
    [25.774252, -80.190262],
    [18.466465, -66.118292],
    [32.321384, -64.75737]
  ],
  "feed2": [
    [32.321384, -64.75737],
    [36.321384, -88.75737]
  ],
  "feed3": [
    [20.466465, -68.118292],
    [34.321384, -66.75737],
    [27.774252, -82.190262]
  ]
};

function MVCArrayBinder(mvcArray) {
  this.array_ = mvcArray;
}
MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function(key) {
  if (!isNaN(parseInt(key))) {
    return this.array_.getAt(parseInt(key));
  } else {
    this.array_.get(key);
  }
}
MVCArrayBinder.prototype.set = function(key, val) {
  if (!isNaN(parseInt(key))) {
    this.array_.setAt(parseInt(key), val);
  } else {
    this.array_.set(key, val);
  }
}

function marFunc(event) {
  var path = poly.getPath();
  path.push(event.latLng);
  var len = path.getLength();
  var marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
    draggable: true
  });
  marker.bindTo('position', poly.binder, (len - 1).toString());
}

var poly;
var map;

function initialize() {
  var polyOptions = {
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3,
    map: map
  };
  poly = new google.maps.Polyline(polyOptions);

  var bounds = new google.maps.LatLngBounds();
  map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(25.774252, -80.190262),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var markers = new Array();
  var polycoordinate = Array();

  poly.binder = new MVCArrayBinder(poly.getPath());
  for (var i in locations) {
    for (j in locations[i]) {
      var evt = {};
      evt.latLng = new google.maps.LatLng(locations[i][j][0], locations[i][j][1]);
      bounds.extend(evt.latLng);
      marFunc(evt);
    }
  }
  poly.setMap(map);
  map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

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 properly formatting quotes in JSON to activate a link

I am working with a JSON configuration file that looks like this: "type": "script", "label": "coreapps.archivesRoom.printSelected", "script": "emr.fragmentActionLink(${project.parent.artifactId},\"downloadPatientHistory\", &bs ...

Obtain decrypted information from the token

I am facing difficulty in retrieving decrypted user data for the current user. Every time a user logs in, they receive a token. After logging in, I can take a photo and send it to the server. Looking at my code, you can see that this request requires a to ...

Error code 405 (METHOD NOT ALLOWED) is received when attempting to make a post request to an API

Struggling to develop a basic front end that can communicate with my API. The API functions properly as I am able to retrieve and send data using the POSTMAN client. Fetching data from the server and displaying it on the frontend works fine, but encounteri ...

Using a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below. let f = { a: 3, printMyBrother() { console.log(X) } }.printMyBrother f() ...

display the $scope as undefined in an angular application

Below is my code snippet: var exchange = angular.module('app', []); exchange.controller('ExchangeController', ExchangeController); function ExchangeController($scope, $http) { $scope.items = []; $http ...

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...

Fade or animate the opacity in jQuery to change the display type to something other than block

I am currently using display: table and display: table-cell to vertically align multiple divs. However, I have encountered an issue when animating the opacity with jQuery using either fadeTo() or fadeIn. The problem is that it always adds inline style di ...

Traverse through the keys and values of a JSON object using JavaScript

I have a json string that needs to be parsed in a specific way. The structure of the json is as follows: { "a": [{ "b": [ ["c"], [] ], "d": [ [], [] ], "e": [ [], ["f"] ], "g": [ [], ...

Submit a document through a jQuery post method in conjunction with PHP

Is there a way to upload a file without using a form and instead utilizing $.post method to transfer the file? I suspect that the issue lies within the PHP code, although I can't be certain. <input type='file' id='inpfile'> ...

What is the proper way to confirm the authenticity of a captcha code

hey there, I'm struggling with my captcha code. The issue is that it still accepts wrong captchas when entered in the input box. Can someone guide me on how to validate the wrong captcha entry? Here's my form code: <p class="Captcha" style=" ...

Is there a way to detect esbuild's build errors and execute a script in response?

Does anyone know how to handle esbuild's build error and trigger a script afterward? I'm integrating it into my workflow with npm, VSCode, and pure JavaScript. I've searched everywhere but haven't found any information on this specific ...

What are the benefits of using multiple image display in React JS?

Can someone explain to me the process of displaying multiple images in React.js? I am attempting to load an image using canvas and have tried the following code: https://codesandbox.io/s/o4o98kwy0y class App extends Component { constructor() { sup ...

Utilize recursive and for loop methods for parsing JSON efficiently

I have a JSON file that requires parsing. I'm attempting to implement a recursive method for this task. The current JSON data is structured as shown below: Item 01 SubItem 01 InnerSubItem 01 Item 02 SubItem 01 InnerSubItem 01 Unfortunately, t ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

Sending a string array to MVC controllers through ajax

I've been struggling to pass a list of strings from a multiple select to the controller. Despite seeming like a simple requirement, I've spent hours trying to figure it out without success. I've done some research on this but haven't be ...

Add a square div in every direction around the existing content in an HTML file

Begin by locating square number 1. Once you press the + symbol above square 1, square 2 will appear. From there, you can click the + on the right side of square 2 to reveal square 3. Is it possible to achieve this sequence? If so, what is the best way to ...

SailsJS fails to transpile Bootstrap.js in a timely manner

In my backend development with Sails JS, I am utilizing ES6/7 and have created a class to handle background tasks. After reading a post on StackOverflow (link), it was recommended to initiate background tasks in config/bootstrap.js. Following this advice, ...

Reactjs is experiencing issues with the data mapping function

Currently, I am developing with Reactjs and utilizing the nextjs framework. In my current project, I am working on fetching data from a specific URL (https://dummyjson.com/products) using the map function. However, I encountered an error message: TypeError ...

The deployed MVC code encountered an unexpected token "u" in the JSON at position 0

I have a MVC 5 application that is functioning well in the development environment. However, when I publish and deploy it to the testing server (or any other server), I encounter a JavaScript error when clicking on the login button: Uncaught SyntaxError ...