Update in the Marker Coordinates database

Asked

Viewed 939 times

2

Here’s the thing, I have a map where several dots are generated, thus tracing a route... Only now I need to edit these points by the map itself, like I have to do it in a way that I move them markers and automatically record in the database the latitude and longitude of the point I’m moving...

RotaMaps

<script type="text/javascript">
    jQuery(function() {

        var stops = [];

        $('.waypoints').each(function() {
            lat = $(this).attr('lat') * 1;
            lon = $(this).attr('lon') * 1;

            stops.push({"Geometry": {"Latitude": lat, "Longitude": lon}});
        });

        console.log(stops);

        var map = new window.google.maps.Map(document.getElementById("map"));
        var directionsDisplay = new window.google.maps.DirectionsRenderer();
        var directionsService = new window.google.maps.DirectionsService();

        directionsDisplay.setPanel(document.getElementById("directionsPanel"));
        Tour_startUp(stops);

        window.tour.loadMap(map, directionsDisplay);
        window.tour.fitBounds(map);

        if (stops.length > 1)
            window.tour.calcRoute(directionsService, directionsDisplay);
    });

    function Tour_startUp(stops) {
        if (!window.tour)
        window.tour = {
            updateStops: function(newStops) {
            stops = newStops;
            },
            // map: google map object
            // directionsDisplay: google directionsDisplay object (comes in empty)
            loadMap: function(map, directionsDisplay) {
                var myOptions = {
                zoom: 13,
                center: new window.google.maps.LatLng(-3.056833, -60.004703), // default to Manaus
                mapTypeId: window.google.maps.MapTypeId.ROADMAP
                };
                map.setOptions(myOptions);
                directionsDisplay.setMap(map);
            },

            fitBounds: function(map) {
                var bounds = new window.google.maps.LatLngBounds();

                // extend bounds for each record
                jQuery.each(stops, function(key, val) {
                    var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
                    //console.log(myLatlng);return
                    bounds.extend(myLatlng);
                });
                map.fitBounds(bounds);
            },

            calcRoute: function(directionsService, directionsDisplay) {
                var batches = [];
                var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
                var itemsCounter = 0;
                var wayptsExist = stops.length > 0;

                while (wayptsExist) {
                    var subBatch = [];
                    var subitemsCounter = 0;

                    for (var j = itemsCounter; j < stops.length; j++) {
                        subitemsCounter++;
                        subBatch.push({
                            location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
                            stopover: true
                        });
                        if (subitemsCounter == itemsPerBatch)
                            break;
                        console.log(stops[j].Geometry.Latitude);
                    }

                    itemsCounter += subitemsCounter;
                    batches.push(subBatch);
                    wayptsExist = itemsCounter < stops.length;
                    // If it runs again there are still points. Minus 1 before continuing to
                    // start up with end of previous tour leg
                    itemsCounter--;
                }

                // now we should have a 2 dimensional array with a list of a list of waypoints
                var combinedResults;
                var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
                var directionsResultsReturned = 0;

                for (var k = 0; k < batches.length; k++) {

                    var lastIndex = batches[k].length - 1;
                    var start = batches[k][0].location;
                    var end = batches[k][lastIndex].location;

                    // trim first and last entry from array
                    var waypts = [];
                    waypts = batches[k];
                    waypts.splice(0, 1);
                    waypts.splice(waypts.length - 1, 1);

                    var request = {
                        origin: start,
                        destination: end,
                        waypoints: waypts,
                        travelMode: window.google.maps.TravelMode.DRIVING
                    };
                    //console.log(request);
                    (function(kk) {
                        directionsService.route(request, function(result, status) {
                            if (status == window.google.maps.DirectionsStatus.OK) {
                                var unsortedResult = {order: kk, result: result
                            };
                            unsortedResults.push(unsortedResult);

                            directionsResultsReturned++;

                            if (directionsResultsReturned == batches.length){ // we've received all the results. put to map
                                // sort the returned values into their correct order
                                unsortedResults.sort(function(a, b) {
                                    return parseFloat(a.order) - parseFloat(b.order);
                                });
                                var count = 0;
                                for (var key in unsortedResults) {
                                    if (unsortedResults[key].result != null) {
                                        if (unsortedResults.hasOwnProperty(key)) {
                                            if (count == 0) // first results. new up the combinedResults object
                                                combinedResults = unsortedResults[key].result;
                                            else {
                                                // only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
                                                // directionResults object, but enough to draw a path on the map, which is all I need
                                                combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
                                                combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);

                                                combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
                                                combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
                                            }
                                            count++;
                                        }
                                    }
                                }
                                directionsDisplay.setDirections(combinedResults);
                                }
                            }
                        });
                    })(k);
                }
            }
        };
    }
</script>
  • You need to implement an object collection, and assign an Id (even from the BD) to each Waypoint and Marker, when you move one, it will move an object, and this object needs a callback to send the coordinate via json/ajax to the database.

  • I don’t know if this is the case with each Waypoint/Marker, or just Marker.

  • But I still haven’t been able to get Mark(Waipoints) to move... you know how to do that ?

  • I’m making the necessary changes, to post a reply.

  • Dude, here we have a problem, the initial positions, come from the DOM, if you change these coordinates, in the DOM, will remain this information, you declared the points as "stops". On the map when we change, it will lose the consistency of the DOM data, it would be interesting to post your HTML, to see what we can do for DOM present the same information when you drag a Marker, or maybe this is not even necessary, what do you think?

  • <body>&#xA; <?php&#xA; $waypts='';&#xA; foreach ($listaItinerario as $valor) {&#xA; $waypts.="<input type='hidden' class='waypoints' name='local[]' lat='" . $valor['localLatitudePonto'.$x] . "' lon='" . $valor['localLongitudePonto'.$x] . "'>";&#xA; } &#xA; /*NESTA LINHA ESTÁ SETADA A LONGOITUDE E LATITUDE DA EMPRESA*/&#xA; $waypts.="<input type='hidden' class='waypoints' name='local[]' lat='-3.122993' lon='-59.980144'>";&#xA; echo $waypts;&#xA; ?>&#xA; <div class="contentMap"></div> &#xA; <div id="map"></div>&#xA; <div class="contentMap"></div> &#xA;</body>

Show 1 more comment

1 answer

2

I’ll just give you the way of the thing, the question is too wide.

To make markers draggable:

Source:https://developers.google.com/maps/documentation/javascript/examples/directions-draggable

var rendererOptions = { draggable: true}
var directionsDisplay = new window.google.maps.DirectionsRenderer(rendererOptions);

Create a System Event on map startup to know that Marker has changed:

google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
    salvaNoBd(directionsDisplay.getDirections());
});

Declare the function called by the Event Listener:

Source:http://api.jquery.com/jquery.post/

function salvaNoBd(coordenadas) {
    $.post( "examplo.php", coordenadas);
}

Then just treat the coordinates sent by the post in php, Asp, or whatever language you use to communicate with the database, one detail is that you need to implement a way to pass an ID to each marketer, and use this ID as a post parameter as well.

But the way you are doing, you are passing to the DOM, already without any identification, and this you will need to implement in your code, as I do not have it in full, I can not answer you in full.

  • I entered the link you gave me and I managed to run here on my machine, but it only accepts an origin, a destination and 8 waypoints... in my case, I have routes with up to 40 waypoints... And I haven’t been able to adapt the draggable: true in my code...

  • I managed to drag the markers, but when more than 10 markers on the map is erased some and loads only the top 10...

  • Take a look here: https://developers.google.com/maps/documentation/javascript/directions?hl=pt-br#Draggabledirections

  • In Api V2, uses 25, V3 reduced to 8, I took a look on the net, but I found nothing interesting, who knows, for your case, be interesting to use some other web service.

  • I know it’s been a long time, but I use a code to pass 8 points + start and end. The code in question is on this page: http://www.geocodezip.com/v3_directions_multipleWayPts_CustomMrkrs_busRoute.html From what I understand, this code creates batches of 10 points each, and when Maps returns the routes, it joins everything in one route only in the view. Works great.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.