I have an issue with mapbox direction plugin, on a rails app. When I load the page where the map is, I have this error :
Uncaught TypeError: mapboxgl.Directions is not a constructor
at HTMLDocument.<anonymous> (travel.self-10030a4….js?body=1:34)
at fire (jquery.self-bd7ddd3….js?body=1:3233)
at Object.fireWith [as resolveWith] (jquery.self-bd7ddd3….js?body=1:3363)
at Function.ready (jquery.self-bd7ddd3….js?body=1:3583)
at HTMLDocument.completed (jquery.self-bd7ddd3….js?body=1:3618)
Here is the code for my map :
var map;
var directions;
// token access for MAPBOX GL
mapboxgl.accessToken = 'pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw';
// generate map
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [-96, 37.8],
zoom: 5
});
// center map on selected marker
map.on('click', 'markers', function (e) {
map.flyTo({center: e.features[0].geometry.coordinates});
});
// change mouse action on enter / leave in marker
map.on('mouseenter', 'markers', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'markers', function () {
map.getCanvas().style.cursor = '';
});
// Directions
var directions = new mapboxgl.Directions({
unit: 'metric',
profile: 'driving',
container: 'directions'
});
$.ajax({
dataType: 'json',
url: grabTravelData(),
success: function(data) {
geojson = data;
map.addSource("markers", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": data
}
});
map.addLayer({
"id": "markers",
"type": "circle",
"source": "markers",
"paint": {
"circle-radius": 7,
"circle-color": "#ff7e5f"
},
});
// center map on markers
var bounds = new mapboxgl.LngLatBounds();
data.forEach(function(feature) {
bounds.extend(feature.geometry.coordinates);
});
map.fitBounds(bounds);
// test - set direction for each marker to following marker
for(var i = 0; i < data.lenght; i++) {
var last = data.length - 1
var from = data[i];
var to = data[i + 1];
directions.setOrigin(from);
if(to != from) {
directions.setDestination(to);
} else {
directions.setDestination(from);
}
}
}, error: function(data) {
console.log(data + ' error');
}
});
In this code, with a for loop I try to create a routes between each markers with the following marker.
In the header of the app I import mapbox :
<script src='https://api.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet' />
<script src="https://cdn.jsdelivr.net/places.js/1/places.min.js"></script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.css' type='text/css' />
Doest someone know what is this error ?
The proper way to use the Mapbox GL directions is
var directions = new MapboxDirections({
accessToken: 'YOUR-MAPBOX-ACCESS-TOKEN',
unit: 'metric',
profile: 'cycling'
});
map.addControl(directions);
For more details refer the API Documentation
Related
<div id="map">
</div>
<script>
var map, heatmap;
var heatpoints = [];
function initMap(){
$.ajax({
type: 'GET',
url: '/show_heat_map',
dataType: 'json',
data: {},
success: function(data, status, xhr){
$.each(data["locations"], function(index, item){
if (index == 0) { //To get the center point of heat map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: item["latitude"],
lng: item["longitude"]
},
mapTypeId: 'roadmap' //roadmap, satellite, hybrid, terrain
});
}
var lat = item["latitude"];
var lng = item["longitude"];
if (lat != null && lng != null) {
heatpoints.push(new google.maps.LatLng(lat, lng)); //all the heatpoints
}
});
console.log("HEAT POINTS IS "+heatpoints);
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatpoints,
map: map
});
},
error: function(error){
console.log("Error");
}
});
}
</script>
<%= javascript_include_tag 'https://maps.googleapis.com/maps/api/js?key='+Rails.application.secrets.google_maps_api_key+'&libraries=visualization&callback=initMap' %>
The initMap gets called when the pdf is rendered. But it doesnt reach the map loading. If this doesnt work, is there a way i can do the same using any other gem like prawn. I felt wkhtmltopdf is very simple.
This question already has answers here:
Google Maps API v3: How to remove all markers?
(32 answers)
Closed 4 years ago.
Could someone be kind enough to share how I can clear the markers in google map before refreshing it with a new set of markers?
In my map, I'm adding markers from an array that contains name, lat and long. The name can be picked from a drop down menu, and then all the markers for that name are added to the page.
Prtoject : Asp.Net Mvc
Link image: https://i.hizliresim.com/V927Py.jpg
When the user adds markers, the previous set of markers remain. I'd like to remove any existing markers before adding the new set.
After reading the documentation, I tried this:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model List<Project_Map.Models.KONUM>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Marker Icons</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<style>
#map_wrapper {
height: 700px;
}
#map_canvas {
width: 100%;
height: 100%;
}
</style>
<div id="map_wrapper">
<div class="mapping" id="map_canvas">
</div>
</div>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
jQuery(function ($) {
var script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBT56XlfxnK2OB4K93vWdrZci_CKjZyQOM&callback=initMap";
document.body.appendChild(script);
});
</script>
<!-- Google Maps Kodu -->
<script type="text/javascript">
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'<img src="#IMG_SRC#" />' +
'</div>' +
//'<h2 id="firstHeading" class="firstHeading">#PERSONEL#</h2>' +
'<div id="bodyContent">' +
'<b>Mesafe: </b>#MESAFE# Km<br />' +
'<b>Tarih: </b> #TARIH#' +
'</p>' +
'</div>' +
'</div>';
$(document).ready(function () {
initMap();
});
function initMap() {
var mapCenter = { lat: 39.684536, lng: 35.337094 };
var map = new google.maps.Map(document.getElementById('map_wrapper'), {
zoom: 6,// haritanın yakınlık derecesi
center: mapCenter, // haritanın merkezi
mapTypeId: google.maps.MapTypeId.HYBRID
});
var infoWindow = new google.maps.InfoWindow();
setInterval(function () {
$.ajax({
url: '#Url.Action("GetMapLocations", "Konum")',
type: "POST",
success: function (data) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var position = {
lat: parseFloat(json[i].lat.replace(',', '.')),
lng: parseFloat(json[i].lng.replace(',', '.'))
};
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.BOUNCE,
map: map,
});
// infoWindow içeriğini replace et
var cs = contentString;
cs = cs.replace("#PERSONEL#", json[i].name);
cs = cs.replace("#MESAFE#", json[i].mesafe);
cs = cs.replace("#TARIH#", json[i].tarih);
cs = cs.replace("#IMG_SRC#", json[i].img);
google.maps.event.addListener(marker, 'click', (function (marker, cs, infoWindow) {
return function () {
infoWindow.setContent(cs);
infoWindow.open(map, this);
passive: true;
};
})(marker, cs, infoWindow));
};
},
error: function (data) { alert("Malesef Sunucunuza Ulaşamıyoruz. Lütfen Tekrar Deneyiniz..."); },
});
}, 5000);
};
</script>
</body>
</html>
You have to set up an array, where you can store the added marker
var gmarkers = [];
If you add a marker you have to store the marker object in the array.
gmarkers.push(marker);
If you want to remove these markers you can use something like:
function removeMarker() {
if (gmarkers.length > 0) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i] != null) {
gmarkers[i].setMap(null);
}
}
}
gmarkers = [];
}
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
$(document).ready(function () {
google.setOnLoadCallback(drawChartCountry);
$("a[href='#tab11']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartCountry
});
});
$("a[href='#tab21']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartDevice
});
});
$("a[href='#tab31']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartVersion
});
});
function drawChartCountry() {
$.post('/AppDashboard/GetCountryChart', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Country');
tdata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
//pieSliceText: 'label',
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart_country'));
chart.draw(tdata, options);
});
}
function drawChartDevice() {
$.post('/AppDashboard/GetDeviceChart', {},
function (data) {
var devicedata = new google.visualization.DataTable();
devicedata.addColumn('string', 'Device');
devicedata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
devicedata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart-device'));
chart.draw(devicedata, options);
});
}
function drawChartVersion() {
$.post('/AppDashboard/GetVersionChart', {},
function (data) {
var versiondata = new google.visualization.DataTable();
versiondata.addColumn('string', 'Version');
versiondata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
versiondata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
//pieSliceText: 'label',
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart-version'));
chart.draw(versiondata, options);
});
}
});
I have set google chart inside a widget but the sad part is responsive is not working.When i resize it to mobile size the chart data exceeds my widget.Kindly help me with this and if you need more info lemme know,thanks in advance :)
in my ror app(ruby on rails),one of page google.js.erb function show google map, i add add position function,i use extjs frame,however i encounter some stronger problem, relative code is below
Ext.onReady(function () {
var mapOptions =
{
zoom: 6,
center: new google.maps.LatLng(30.26, 120.19),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
mapTypeControl: true
};
var map = new google.maps.Map(Ext.getDom('mapDiv'), mapOptions);
var googlemappanel=Ext.create('Ext.panel.Panel', {
items: [
{
xtype: 'panel',
region: 'east',
items: [
Ext.create('Ext.form.Panel', {
id: 'zone-form',
items: [
{xtype:"textfield",fieldLabel: '<%= t('code') %>',name: "code", id: 'zoneid'}
],
buttons: [{
handler: function(){
Ext.getCmp('zone-form').getForm().submit({
url : 'basestation_edit',
success : function(form, action){
var base=action.result.griddata
for(var i=0; i<action.result.griddata.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(base[i].latitude,base[i].longitude),
map: map
});
google.maps.event.addListener(marker, "click", function(event) {
Ext.getCmp('zoneid').setValue(base[i].id);
})
}
}
....
when i submit the form,google marker is added to the map. however when i click the marker, firebug throw out TypeError: base[i] is undefined error, google marker is added normal, it seems variable i is recovery,set global i don't solve the problem。
any help!
i want to make the markers clustered with markerClusterer but i cannot get the map instance with jquery ui map . js
tried:
var map = $('#map_canvas').gmap('getMap');
or
var map = $('map_canvas').gmap('get', 'map');
and after:
var markerCluster = new MarkerClusterer(map, allMarkers);
but with errors
Thank you
Tried this . No Errors but no clusters...
$('#map_canvas').gmap({ 'callback': function () {
var self = this;
$.getJSON('Data/markers.json', function (data) {
$.each(data.markers, function (i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude,marker.longitude)}).click(function () {
$.ajax({
type: "GET",
url: "/LocoMap/LocoMap/InfoMobilePartialView/",
data: { latitude: marker.latitude, longitude: marker.longitude},
success: function (data) {
$("#marker-info").remove();
$(document.body).append("<div id='marker-info' data-role ='page'> </div>");
var $contentDiv = $("#marker-info");
$contentDiv.html(data).trigger('create');
$.mobile.changePage("#marker-info", { changeHash: false, type: "get", transition: 'pop',rel:"external" });
},
error: function (errorData) { onError(errorData); }
});
});
});
});
self.set('MarkerClusterer', new MarkerClusterer(this.get('map'), this.get('markers')));
}});
$('#map_canvas').gmap({'zoom': 2, 'disableDefaultUI':true}).bind('init', function(evt, map) {
$.getJSON( 'Data/markers.json', function(data) {
$.each( data.markers, function(i, m)
$('#map_canvas').gmap('addMarker', { 'position': new google.maps.LatLng(m.latitude, m.longitude), 'bounds':true } );
});
});
$('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map,$(this).gmap('get', 'markers')));
});
with no errors and no clusters
it seems **$(this).gmap('get', 'markers')));** returns Array[0]