Jump to content

need help to set current GPS position in existing map


pmonstad

Recommended Posts

I have a map running at https://fjellturblogg.no/kart

What I want is an option to turn on/off the current GPS position, to make it possible to navigate the map.

I have found an example of a working HTML5 example of how this can be implemented at: https://jsfiddle.net/31ws6z37/1/

What I really need some help to fix, is how to put this into my main script. I only need a pointer or blue circle to represent current position in the map. An option to turn this feature on/off is also welcome. I will also need a possibility to refresh the map/current GPS position every 30 seconds.

My main scrips looks like this:

jQuery(document).ready(function($) {
	var mapContainer = ".nu-map-container";
    var randId = new Date().getTime()*Math.random()*1000000;
    var mapId = "map-"+randId;
    var graphId = "graph"+randId;

    $(mapContainer).each(function(i, el) {        
        $(el).find(".nu-map").attr("id", mapId);
        $(el).find(".nu-graph").attr("id", graphId);

        // Get all default settings from parent
        var columnsData  = $(el).attr("data-columns") || "{}";
        columnsData = JSON.parse(columnsData);
        var settingsData = $(el).attr("data-settings") || "{}";
        settingsData = JSON.parse(settingsData);
        var locData = $(el).attr("data-loc"); // Center marker name;
        var viewData = $(el).attr("data-view") || "all"; // Display all markers or not
        var viewDataArray = viewData.split(",");
        var geoJSONUrl   = $(el).attr("data-geom");
        var gpxUrl       = $(el).attr("data-gpx"); // TODO: Temp before use drive url
        // AJAX Request settings
        var nonce        = $(el).attr("data-nonce");
        var action       = $(el).attr("data-action");
        var tablePressId = $(el).attr("data-table");

        // Marker coming in form [east, north], selected zone is 33N [https://prnt.sc/qnu3sy]
        var rawMarkers = [
            {
                east: -26078.16,
                north: 6636791.98,
                title: "static-marker-1",
                url: "https://leafletjs.com/examples/layers-control/"
            },
            {
                east: -19405.98,
                north: 6645694.74,
                title: "static-marker-1",
                url: "https://leafletjs.com/examples/layers-control/"
            }
        ];

        // Layer of markers
        var poiLayer = L.layerGroup();
        var tracksLayer = L.layerGroup();
        // Store markers list retrieve from database
        var markers = [];
        // Trigger WP AJAX to get the raw marker data
        if (tablePressId) {
            createMarkers(poiLayer);
        }        

        // NOTE: use center name in shortcode
        /*var east = (settingsData.center || "7164014, 400784").split(",")[1];
        var north = (settingsData.center || "7164014, 400784").split(",")[0];*/
        var east = ("7164014, 400784").split(",")[1];
        var north = ("7164014, 400784").split(",")[0];
        // Set width height
        $("#"+mapId).css({
            "width": settingsData.width || "100%",
            "height": settingsData.height || "400px",
        });
        // Init base map
        var map = L.map(mapId, {
            //center: [59.8939529,10.6450337], // capital Oslo
            center: convertUtmToLL(east, north),
            zoom: settingsData.zoom || 4,
            layers: [poiLayer, tracksLayer],
            dragging: !L.Browser.mobile, 
            tap: !L.Browser.mobile,
            fullscreenControl: settingsData.fullscreen == "yes",
            fullscreenControlOptions: {
                position: 'topleft'
            }
        });
		
        jQuery(document).on("mouseout", ".map-scroll", function() {
			jQuery(".nu-map").removeClass("map-scroll");
		});
        
        $(document).on("mousedown", ".leaflet-control-zoom-fullscreen", function() {
            $(".nu-map").removeClass("map-scroll");
        });
        //disable default scroll 
        map.scrollWheelZoom.disable();

        mapId = "#"+mapId;
        $(mapId).bind('mousewheel DOMMouseScroll', function (event) {
            event.stopPropagation();
            if (event.ctrlKey == true) {
                event.preventDefault();
                map.scrollWheelZoom.enable();
                $(mapId).removeClass('map-scroll');
                setTimeout(function(){
                    map.scrollWheelZoom.disable();
                }, 1000);
            } else {
                // Only add map-scroll if the screen is not in fullscreen
                if (jQuery(".nu-map").is(":fullscreen")) {
                    map.scrollWheelZoom.enable();
                    $(mapId).removeClass('map-scroll');
                    setTimeout(function(){
                        map.scrollWheelZoom.disable();
                    }, 1000);
                } else {
                    map.scrollWheelZoom.disable();
                    $(mapId).addClass('map-scroll');
                }                
            }
        });

        $(window).bind('mousewheel DOMMouseScroll', function (event) {
           $('#map').removeClass('map-scroll');
        })
        // Load geojson masked
        loadGeoTiles(geoJSONUrl);        

        var overlays = {
            "Ruter": tracksLayer,
            "Punkter": poiLayer
        };

        L.control.layers(null, overlays).addTo(map);

        function loadGeoTiles(geoUrl, tileUrl, attribution) {
            $.getJSON(geoUrl, function(res) {
                var geom = res;

                var osmUrl = 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png';
                var osmAttribution = 'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)';

                var openTopoMap = L.TileLayer.boundaryCanvas(osmUrl, {
                    boundary: geom, 
                    attribution: osmAttribution,
                    trackAttribution: true
                });//.addTo(map);

                var norgeskartMap = L.tileLayer('https://opencache.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=topo4&zoom={z}&x={x}&y={y}', {
                    attribution: '<a href="http://www.kartverket.no/">Kartverket</a>'
                }).addTo(map);

                var baseLayers = {
                    "Topo": openTopoMap,
                    "norgeskart": norgeskartMap
                };

                //L.control.layers.addBaseLayer(baseLayers).addTo(map);
            })
        }

        // Convert UTM [east, north] to [lat,lng]
        function convertUtmToLL(east, north, zone, band) {
            var item = L.utm({x: east, y: north, zone: zone || 33, band: band || 'N'});
            var coord = item.latLng();

            return coord;
        }

        // Convert and create markers 
        function createMarkers(layer) {
            jQuery.ajax({
                type: "POST", 
                url: nu_ajaxurl,
                data : {
                    action: action,
                    tableId: tablePressId,
                    nonce: nonce
                },
                success: function(data) {
                    // Use column data above, -1 for correct zero-based index, check _main.js NOTE
                    var rawMarkers = data.slice(1); // Remove header
                    
                    var nameCol = columnsData.name-1 || 0;
                    var urlCol = columnsData.url-1 || 0;
                    var positionCol = columnsData.position-1 || 0;
                    var gpxCol = columnsData.gpx-1 || 0;
                    var heightCol = columnsData.height-1 || 0;
                    // Remember to check against loc and view
                    var foundLoc = rawMarkers.filter(function(m) {
                        return locData && m[nameCol] && m[nameCol].toLowerCase() == locData.toLowerCase();
                    })[0];
                    if (foundLoc) {
                        var pos = foundLoc[positionCol].split(","); //[north, east]
                        var llCoord = convertUtmToLL(parseFloat(pos[1]), parseFloat(pos[0]), 33, 'N'); // 33N is default for norway coord, 
                        map.panTo(llCoord);
                    }

                    for (var i = 0; i < rawMarkers.length; i++) {
                        // exclude the position empty
                        var markerData = rawMarkers[i];
                        if ( markerData[positionCol] ) {                                                
                            var linkUrl = $(markerData[urlCol]).is("a") ? $(markerData[urlCol]).attr("href") : "";
                            var popupTemplate = '<div class="l-popup">';
                            if (linkUrl) {
                                popupTemplate += "<label><a href='"+linkUrl+"'>"+markerData[nameCol]+"</a></label>";
                            } else {
                                popupTemplate += "<label>"+markerData[nameCol]+"</label>";
                            }
                            popupTemplate += "<br><span>"+markerData[heightCol]+"</span>";

                            var pos = markerData[positionCol].split(","); //[north, east]
                            var llCoord = convertUtmToLL(parseFloat(pos[1]), parseFloat(pos[0]), 33, 'N'); // 33N is default for norway coord, 
                            var marker = L.marker(llCoord).bindPopup(popupTemplate);
                            
                            // Only generate chart on foundLoc, or else many of charts is created
                            // Check against the view option
                            if (!viewData || viewData.toLowerCase() == "all") {
                                marker.addTo(layer);
                                // Find gpxURL attached to each 
                                generateTracker(markerData[gpxCol], !!foundLoc);
                                //generateTracker(gpxUrl+"Krakkanuten5.gpx");
                            } else {
                                viewDataArray = viewDataArray.map(function(v) { return (v.trim() || "").toLowerCase(); });
                                if (viewDataArray.indexOf(markerData[nameCol].toLowerCase()) != -1) {
                                    marker.addTo(layer);
                                    // Find gpxURL attached to each 
                                    generateTracker(markerData[gpxCol], !!foundLoc);
                                    //generateTracker(gpxUrl+"Krakkanuten5.gpx");
                                }
                            }

                            marker.on('mouseover', function (e) {
                                this.openPopup();
                            });
                            marker.on('click', function (e) {
                                this.openPopup();
                            });                            
                        }                   
                    }

                    return markers;     
                },
                error: function() {
                    updateMessage("Can't fetch the table header");
                    console.log(data);
                }
            });        
        }

        // Get data from gpx file
        function generateTracker(fileUrl, generateGraph) {
            // Break on empty
            if (!fileUrl) {
                return;
            }
            var _fileUrl = generateDriveUrl(fileUrl) ? generateDriveUrl(fileUrl) : fileUrl;
            // Try to find the 
            $.get(_fileUrl, function(result) {
                var gpxContent = result.documentElement ? result.documentElement.outerHTML : result;
                if (gpxContent) {
                    //Create gpxParser Object
                    var gpx = new gpxParser(); 
                    //parse gpx file from string data
                    gpx.parse(gpxContent); 
                    
                    if(gpx.waypoints.length > 0) {
                      $('#part-waypoints').addClass('part-visible');
                    } else {
                      $('part-waypoints').removeClass('part-visible');
                    }

                    gpx.waypoints.forEach(function(wpt) {
                        tracksLayer.addLayer(L.marker([wpt.lat, wpt.lon]).bindPopup(wpt.name));

                    });

                    if(gpx.tracks.length > 0) {
                      $('#part-tracks').addClass('part-visible');
                    } else {
                      $('#part-tracks').removeClass('part-visible');
                    }
                    gpx.tracks.forEach(function(track){
                        buildPolyline(track.points);
                    });

                    if(gpx.routes.length > 0) {
                      $('#part-routes').addClass('part-visible');
                    } else {
                      $('#part-routes').removeClass('part-visible');
                    }
                    gpx.routes.forEach(function(route){
                        buildPolyline(route.points);
                    });

                    // GRAPH: Draw the highchart 
                    var track = gpx.tracks[0];
                    if (track && generateGraph) {
                        drawGraph(track.elevation.elevation, track.distance.cumul, graphId, settingsData);
                    }                    
                }
            })
        }

        function generateDriveUrl(url) {
            var id = url.match(/[-\w]{25,}/);

            if (id && url.indexOf("drive.google.com") != -1) {
                return "https://cors-anywhere.herokuapp.com/https://drive.google.com/uc?export=download&id="+id;
            }

            return "";
        }

        function buildPolyline(points){
            var latlngs = [];

            points.forEach(function(pt){
                let p = [pt.lat, pt.lon];
                latlngs.push(p);
            });

            //let color = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
            var color = settingsData.line_color;
            var polyline = L.polyline(latlngs, {
                color: color || "#d93025",
                weight: 4
            });        

            polyline.addTo(tracksLayer);
            //tracksLayer.addLayer(polyline);
            //map.fitBounds(tracksLayer.getBounds());        
        }
        
        
    });	

    return;            
    
});

 

Link to comment
Share on other sites

One step at a time.

1. Update the code so that you can place a marker at some coordinates. Don't bother trying to geolocate anything. Just hardcode some numbers in there. Make sure it can be placed sometime after the map has been already fully initialized and drawn.
2. Update the code so that you can move that marker to some new coordinates. Again, no geolocation, just hardcode another set of numbers. Start by putting the marker at the first location like before, then use setTimeout have the marker reposition somewhere else 30 seconds later.
3. Update the code so that you can get past the geolocation permission prompt to get the first position. Then use that first position to place the marker at its first location for real.
4. Update the code so that you can "watch" for geolocation changes. Just console.log or alert the new coordinates so you can see it working.
5. Update the code so that the geolocation changes will reposition the marker.

IIRC you don't have to do any "get the location every 30 seconds" work because the browser can simply tell you when the position changes.

Link to comment
Share on other sites

18 hours ago, requinix said:

One step at a time.

1. Update the code so that you can place a marker at some coordinates. Don't bother trying to geolocate anything. Just hardcode some numbers in there. Make sure it can be placed sometime after the map has been already fully initialized and drawn.
2. Update the code so that you can move that marker to some new coordinates. Again, no geolocation, just hardcode another set of numbers. Start by putting the marker at the first location like before, then use setTimeout have the marker reposition somewhere else 30 seconds later.
3. Update the code so that you can get past the geolocation permission prompt to get the first position. Then use that first position to place the marker at its first location for real.
4. Update the code so that you can "watch" for geolocation changes. Just console.log or alert the new coordinates so you can see it working.
5. Update the code so that the geolocation changes will reposition the marker.

IIRC you don't have to do any "get the location every 30 seconds" work because the browser can simply tell you when the position changes.

Hi! Any chance I can pay you to get this working? My knowledge is far too limited.

Link to comment
Share on other sites

2 minutes ago, requinix said:

Not me, no. If you insist that you can't do it yourself then we have a place you can post your job offer, but frankly, if the problem is that your knowledge is "far too limited" then this would be a really good chance to try to do something about that.

Good point, but I do not have the time right now.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.