I'm trying to use Mapbox Static API through their Javascript SDK. I want to upload an external geojson source to my map. I can't figure out a way to do it. I tried following a Mapbox tutorial called Using style parameters with Static Images API.
Here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Demo: Static images with style parameters</title>
<script src="https://unpkg.com/#mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
<style>
.container {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<img id="traffic" src="" alt="Mapbox traffic map" />
</div>
</body>
<script>
const mapboxClient = mapboxSdk({ accessToken: 'API TOKEN' });
const addLayerStyle = {
'id': 'traffic',
'type': 'line',
'source': {
'type': 'geojson',
//'url': 'mapbox://mapbox.mapbox-traffic-v1'
//'url': 'https://raw.githubusercontent.com/zaynaib/chicago-elections/main/election_leaflet/data/chicago-wards.geojson'
},
'source-layer': 'traffic'
};
const request = mapboxClient.static.getStaticImage({
ownerId: 'mapbox',
styleId: 'light-v10',
width: 500,
height: 350,
position: {
coordinates: [-87.6298, 41.8781],
zoom: 12
},
addlayer: addLayerStyle,
before_layer: 'road-label'
});
const staticImageUrl = request.url();
document.getElementById('traffic').src = staticImageUrl;
</script>
</html>
From the docs, "source.url must be a mapbox:// tileset URL, and must be accessible to the access token used in the request. source.type must be either raster or vector"
One solution would be to convert your data to a vector tilest using Tippecanoe then upload your vector file in Mapbox Studio to generate a link that starts with mapbox://
Another option would be to add the GeoJSON to the image as an overlay
Related
I'm building a page that can display a chart of sensor data from a csv file. The user should be able to click on a button to choose a desired csv file from his machine to be displayed on a chart. I'm using the Highcharts library for that. The chart works as desired, but I can only input the csv file in code. When I upload a file and update nothing happens. So how can I make "data.csv" dynamic? My idea was to somehow save it into a global data object, that can then be passed into ajax url. I don't know how to implement this, since this is my very first javascript project.
<!DOCTYPE html> <!-- Write your comments here -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.highcharts.com/highcharts.js"></script> <!-- library include-->
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<title>Airmeter</title>
</head>
<body>
<div id="container"></div>
<form id='form'>
<input type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" id="input" />
<button type='submit'>
update the chart
</button>
</form>
<script>
$.ajax({
type: "GET",
url: "data.csv",
success: function (data) {
setTitle(data)
}
});
function setTitle(raw_data){
let newTitle;
let chart = Highcharts.chart('container', {
chart: {
zoomType: 'xy',
events: {
load: function() {
this.update({
title: {
text: 'Airmeter: '+ newTitle
}
})
}
}
},
xAxis:{
title:{
text: 'Zeit'
}
},
yAxis:{
title:{
text: 'CO2 in ppm'
}
} ,
exporting:{
enabled: true
},
title: {
text: null
},
credits:{
enabled: false
},
data: {
csv: raw_data,
parsed(e) {
newTitle=e[0][1] //set the first column as title of the chart
e.shift()
}
}
});
}
</script>
</body>
</html>
I would really appreciate help. Thanks for your time and have nice day!
If the CSV will always be on your local machine rather than a server, you don't really need to be using an AJAX call and you could use the FileAPI and a CSV parser to pass the data to your setTitle function.
But to help with your approach, try doing these changes to your code:
Add an onChange event to your input, so whenever a file is selected, the javascript code can 'react' to it.
Wrap your AJAX call in the 'change' event handler.
Pass the selected file name to your AJAX request's URL.
In terms of code changes (untested):
<script>
// Add an event listener, so when a file is selected, the graph is drawn again
document.getElementById("input").addEventListener("change", drawGraph, false);
// Wrap your current AJAX call in the event handler
function drawGraph() {
// Obtain the name of the file selected by the user in the <input>
var fileName = document.getElementById('input').files[0].name;
$.ajax({
type: "GET",
url: fileName, // use this name to fetch the selected file
success: function (data) {
setTitle(data)
}
});
}
// Leave the rest of the script block as it is
// ...
</script>
I want to integrate Shutterstock Image Editor in my simple HTML app. So I make a developer account in Shutterstock and create my API Key. Below is my API:
Now I am using above API Key (Consumer Key) in my HTML as describe here. Below is my HTML file code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://s.picdn.net/editor/image/assets/integration.js"></script>
<script>
window.editorInstance = window.Editor({
apiKey: 'e1818-c5e61-74ce1-7ee31-6c7f8-7fb6d',
language: 'en',
image: 'https://www2.shutterstock.com/blog/wp-content/uploads/sites/5/2015/05/volcano-header-1440x960.jpg',
excludeFeatures: ['filters'],
initialPanel: 'text',
logo: true,
logoUrl: 'https://www2.shutterstock.com/base/public/images/logos/logo-shutterstock-de64a370ef.png',
primaryActionText: 'Save and close',
container: document.querySelector('#editor'),
canvas: {
height: 500,
width: 500,
fill: 'rgb(62, 69, 79)'
},
presets: [{
name: 'Icon',
height: 128,
width: 128
}, {
name: 'Book Cover',
height: 1600,
width: 2400
}],
onPrimaryAction: function() {
window.editorInstance.getBase64({
format: 'jpg',
quality: .91
}).then(function(base64) {
// Handle base64 image data
window.editorInstance.hide();
});
}
});
// Launch instance of Editor
window.editorInstance.launch().then(function(editor) {
// Actions
}).catch(function(err) {
// Handle error
});
</script>
After running my above HTML page Editor doesn't render. Below is my console log showing:
Failed to load resource: the server responded with a status of 403 (Forbidden)
and below screen is showing.
Also I visit Fiddle to integrate editor in HTML but this API is using JSFiddle Client. My question is how I implement Shutterstock photo editor in my HTML app. Please let me know what I'm doing wrong in my above code.
You need to contact api [at] shutterstock.com in order to access the Editor - they'll need to manually enable your api key for it.
I need to display Analytics dashboard on my web site. Like export it from google's website to mine.
I already used Reporting API V4
But I only get the login button.
as you can see, the dashboard from analytics are not displayed.
I need to do it with javascript or C#.
My code (based on this link ):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Analytics Reporting </title>
<meta name="google-signin-client_id" content="472734728686-21tqq751d9mdpkopnjmc1dnctf9644qc.apps.googleusercontent.com">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>
<h1> Analytics Reporting</h1>
<p>
<div class="g-signin2" data-onsuccess="queryReports"></div>
</p>
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
var VIEW_ID = '130082935';
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today'
}
],
metrics: [
{
expression: 'ga:sessions'
}
]
}
]
}
}).then(displayResults, console.error.bind(console));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<script src="https://apis.google.com/js/client:platform.js"></script>
</body>
</html>
I would suggest you look at Google Analytics Embed API. It is much easier from a standpoint based on my experience.
How would I make this Google Analytic Embed API chart responsive? I noticed that the demo on this page is reponsive: https://ga-dev-tools.appspot.com/embed-api/basic-dashboard/
I have also seen various ways of doing this with Google Charts here
https://code.google.com/p/google-visualization-api-issues/issues/detail?id=1056
<!doctype html>
<html lang="en">
<head>
<title>Google Charts</title>
<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>
<script>
gapi.analytics.ready(function() {
var ACCESS_TOKEN = 'XXX'; // obtained from your service account
gapi.analytics.auth.authorize({
serverAuth: {
access_token: ACCESS_TOKEN
}
});
var linechart = new gapi.analytics.googleCharts.DataChart({
query: {
ids: 'ga:XXXXXX',
metrics: 'ga:users',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday'
},
chart: {
type: 'LINE',
container: 'line-chart',
options: {
width: '100%',
title: 'Test.com: Visitors over the past 30 days.',
fontSize: 12
}
}
});
linechart.on('success', function(response) {
// response.chart : the Google Chart instance.
// response.data : the Google Chart data object.
});
linechart.execute();
});
</script>
</head>
<body>
<div>
<div id="embed-api-auth-container"></div>
<div id="line-chart" style='width:100%;height:300px;'></div>
</div>
</body>
</html>
I answered this over here
(Google Embed API) How to change chart-table-style width
Basically you just add an option element and assign width of x% within the charts option element
I just noticed the same issue, setting:
options: {
width: '100%'
}
doesn't work when document width changes (only 'TABLE' chart is responsive 'out of the box').
As workaround, you need to trigger a chart redraw on window resize:
window.addEventListener('resize', function() {
linechart.execute();
});
Sidenotes:
linked Google page doesn't seems to use this or whatelse workarounds to have the chart responsive but the behavior is the same;
if you have animations enabled in your chart those animations might be played multiple times on window resize;
I was using google analytics API and I had the same issue but it worked for me by adding
options:{width:'100%'}
chart: {
type: 'LINE',
container: 'timeline',
options: {width: '100%'}
}
I'm dealing with a very annoying issue regarding arcGIS maps service localization.
According to their API I've added the following JS object:
dojoConfig = {
locale: "fr",
parseOnLoad: true
};
and added the following item to the require array:
"dojo/i18n!myApp/nls/jsapi"
When I've made this additions the maps aren't working anymore.
This is my full code:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<script src="http://js.arcgis.com/3.11/"></script>
</head>
<body>
<div id="mapDiv"></div>
</body>
</html>
JS
dojoConfig = {
locale: "fr",
parseOnLoad: true
};
var map;
require([
"esri/map",
"dojo/i18n!myApp/nls/jsapi",
"dojo/domReady!"
], function(Map) {
map = new Map("mapDiv", {
center: [56.049, 38.485],
zoom: 3,
basemap: "streets"
});
});
DEMO
You probably don't have a file called myApp/nls/jsapi.js in your application, so require can't find it and can't run your function that initializes the map.
As the documentation says:
After creating the resource bundle for the new locale, load the resource module
You should read the documentation for dojo/i18n. It makes more clear what you need to do.