I am using am4chart script to plot map and want to use user given geo-coordinate points. I am taking inputs like:
Latitude: <input type="number" name="a" id="a" ><br>
Longitude: <input type="number" name="b" id="b"><br>
<button onclick="point(document.getElementById('a').value,document.getElementById('b').value)">Add</button>
I want to define my function in amchart given script like:
function point(a,b) {
console.log(parseFloat(a));
console.log(parseFloat(b));
var marker = imageSeries.mapImages.create();
<!-- Try to put lat long -->
marker.latitude = parseFloat(a);
marker.longitude = parseFloat(b);
}
But I got error:
Uncaught ReferenceError: point is not defined
at HTMLButtonElement.onclick
How can I pass points data to show marker in the map?
Here is the full script for map plot:
<!-- Chart code -->
<script>
am4core.ready(function() {
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var continents = {
"AF": 0,
"AN": 1,
"AS": 2,
"EU": 3,
"NA": 4,
"OC": 5,
"SA": 6
}
// Create map instance
var chart = am4core.create("chartdiv", am4maps.MapChart);
chart.projection = new am4maps.projections.Miller();
// Create map polygon series for world map
var worldSeries = chart.series.push(new am4maps.MapPolygonSeries());
worldSeries.useGeodata = true;
worldSeries.geodata = am4geodata_worldLow;
worldSeries.exclude = ["AQ"];
var worldPolygon = worldSeries.mapPolygons.template;
<!--worldPolygon.tooltipText = "{name}";-->
worldPolygon.nonScalingStroke = true;
worldPolygon.strokeOpacity = 0.5;
worldPolygon.fill = am4core.color("#eee");
worldPolygon.propertyFields.fill = "color";
var hs = worldPolygon.states.create("hover");
hs.properties.fill = chart.colors.getIndex(9);
// Create country specific series (but hide it for now)
var countrySeries = chart.series.push(new am4maps.MapPolygonSeries());
countrySeries.useGeodata = true;
countrySeries.hide();
countrySeries.geodataSource.events.on("done", function(ev) {
worldSeries.hide();
countrySeries.show();
});
var countryPolygon = countrySeries.mapPolygons.template;
<!--countryPolygon.tooltipText = "{name}";-->
countryPolygon.nonScalingStroke = true;
countryPolygon.strokeOpacity = 0.5;
countryPolygon.fill = am4core.color("#eee");
var hs = countryPolygon.states.create("hover");
hs.properties.fill = chart.colors.getIndex(9);
// Set up click events
worldPolygon.events.on("hit", function(ev) {
ev.target.series.chart.zoomToMapObject(ev.target);
var map = ev.target.dataItem.dataContext.map;
if (map) {
ev.target.isHover = false;
countrySeries.geodataSource.url = "https://www.amcharts.com/lib/4/geodata/json/" + map + ".json";
countrySeries.geodataSource.load();
}
});
// Set up data for countries
var data = [];
for(var id in am4geodata_data_countries2) {
if (am4geodata_data_countries2.hasOwnProperty(id)) {
var country = am4geodata_data_countries2[id];
if (country.maps.length) {
data.push({
id: id,
color: chart.colors.getIndex(continents[country.continent_code]),
map: country.maps[0]
});
}
}
}
worldSeries.data = data;
// Zoom control
chart.zoomControl = new am4maps.ZoomControl();
// Set initial zoom
chart.homeZoomLevel = 4;
chart.homeGeoPoint = {
latitude: 28.644800,
longitude: 77.216721
};
<!--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Marker !!!!!!!!!!!!!!!!!!!!!!-->
// Define marker path
var targetSVG = "M9,0C4.029,0,0,4.029,0,9s4.029,9,9,9s9-4.029,9-9S13.971,0,9,0z M9,15.93 c-3.83,0-6.93-3.1-6.93-6.93S5.17,2.07,9,2.07s6.93,3.1,6.93,6.93S12.83,15.93,9,15.93 M12.5,9c0,1.933-1.567,3.5-3.5,3.5S5.5,10.933,5.5,9S7.067,5.5,9,5.5 S12.5,7.067,12.5,9z";
<!--!!!!!!!!!!!!!!!! Retrieving coordinates of a click !!!!!!!!!!!!-->
chart.seriesContainer.events.on("hit", function(ev) {
console.log(chart.svgPointToGeo(ev.svgPoint));
var coords = chart.svgPointToGeo(ev.svgPoint);
var marker = imageSeries.mapImages.create();
<!-- Try to put lat long -->
marker.latitude = coords.latitude;
marker.longitude = coords.longitude;
console.log(document.getElementById('lat').value);
});
function point(a,b) {
console.log(parseFloat(a));
console.log(parseFloat(b));
<!-- Try to put lat long -->
marker.latitude = parseFloat(a);
marker.longitude = parseFloat(b);
}
<!--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-->
// Add images
var imageSeries = chart.series.push(new am4maps.MapImageSeries());
var imageTemplate = imageSeries.mapImages.template;
imageTemplate.tooltipText = "{title}";
imageTemplate.nonScaling = true;
var marker = imageTemplate.createChild(am4core.Sprite);
marker.path = targetSVG;
marker.horizontalCenter = "middle";
marker.verticalCenter = "middle";
marker.scale = 0.7;
<!--marker.fill = interfaceColors.getFor("alternativeBackground");-->
imageTemplate.propertyFields.latitude = "latitude";
imageTemplate.propertyFields.longitude = "longitude";
<!--imageSeries.data = [ {-->
<!-- "title": "Delhi",-->
<!-- 'latitude': 28.644800,-->
<!-- 'longitude': 77.216721,-->
<!-- "scale": 1-->
<!-- }, {-->
<!-- "title": "Kiev",-->
<!-- "latitude": a,-->
<!-- "longitude": b,-->
<!-- }];-->
var homeButton = new am4core.Button();
homeButton.events.on("hit", function() {
worldSeries.show();
countrySeries.hide();
chart.goHome();
});
homeButton.icon = new am4core.Sprite();
homeButton.padding(7, 5, 7, 5);
homeButton.width = 30;
homeButton.icon.path = "M16,8 L14,8 L14,16 L10,16 L10,10 L6,10 L6,16 L2,16 L2,8 L0,8 L8,0 L16,8 Z M16,8";
homeButton.marginBottom = 10;
homeButton.parent = chart.zoomControl;
homeButton.insertBefore(chart.zoomControl.plusButton);
}); // end am4core.ready()
</script>
Related
please, I'm trying to create with AmCharts 4 chart with multiple data sets. In previous version it is done this way: https://www.amcharts.com/demos/multiple-data-sets/
but I can't find anything how to make it in 4th version.
I use the code from their website.
Everything is ok, next chart I want to add in section starting with comment add ATR -> I need to show it under the original chart.
Thank you very much for any help.
Have a nice day!
var chart = am4core.create("candlestick-chart", am4charts.XYChart);
chart.paddingRight = 20;
// chart.dateFormatter.inputDateFormat = "YYYY-MM-dd";
chart.dateFormatter.inputDateFormat = "x";
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.tooltip.disabled = true;
/*
add default series
*/
var series = chart.series.push(new am4charts.CandlestickSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "close";
series.dataFields.openValueY = "open";
series.dataFields.lowValueY = "low";
series.dataFields.highValueY = "high";
series.dataFields.atr = "atr";
series.dataFields.average_atr = "average_atr";
series.simplifiedProcessing = true;
series.tooltipText = "Open:${openValueY.value}\nLow:${lowValueY.value}\nHigh:${highValueY.value}\nClose:${valueY.value}\nATR:{atr.formatNumber('#.000')}\nAverage ATR:{average_atr.formatNumber('#.000')}";
series.riseFromPreviousState.properties.fillOpacity = 1;
series.dropFromPreviousState.properties.fillOpacity = 0;
chart.cursor = new am4charts.XYCursor();
/*
add scrollbar
*/
// a separate series for scrollbar
var scrollbarSeries = chart.series.push(new am4charts.LineSeries());
scrollbarSeries.dataFields.dateX = "date";
scrollbarSeries.dataFields.valueY = "close";
// need to set on default state, as initially series is "show"
scrollbarSeries.defaultState.properties.visible = false;
// hide from legend too (in case there is one)
scrollbarSeries.hiddenInLegend = true;
scrollbarSeries.fillOpacity = 0.5;
scrollbarSeries.strokeOpacity = 0.5;
var scrollbarX = new am4charts.XYChartScrollbar();
scrollbarX.series.push(scrollbarSeries);
chart.scrollbarX = scrollbarX;
/*
add ATR
-> I need to show it under the original chart
*/
var lineSeriesATR = chart.series.push(new am4charts.LineSeries());
lineSeriesATR.dataFields.dateX = "date";
lineSeriesATR.dataFields.valueY = "atr";
lineSeriesATR.defaultState.properties.visible = false;
// hide from legend too (in case there is one)
lineSeriesATR.hiddenInLegend = true;
lineSeriesATR.fillOpacity = 0.5;
lineSeriesATR.strokeOpacity = 0.5;
chart.data = {!! json_encode($candles) !!};
AmCharts 4 does not have the stock chart implemented yet. You can approximate panels and synced cursor and zoom by using the chart's containers to create additional charts and using the API to make the cursor and scrollbar affect all the charts.
You can create each chart and push them onto the chart container like so:
var container = am4core.create("chartdiv", am4core.Container); //create the container
container.width = am4core.percent(100); //set dimensions and layout
container.height = am4core.percent(100);
container.layout = "vertical";
// ... for each chart
var chart = container.createChild(am4charts.XYChart);
// ..set up as usual
While setting up each chart, you'll need to set up events to sync up zoom events:
// whenever any of the charts is zoomed, we should zoom all other charts
dateAxis.events.on("selectionextremeschanged", function (event) {
syncDateAxes(event.target);
})
// ...
function syncDateAxes(syncWithAxis) {
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
var dateAxis = chart.xAxes.getIndex(0);
if (dateAxis != syncWithAxis) {
dateAxis.events.disableType("selectionextremeschanged");
dateAxis.start = syncWithAxis.start;
dateAxis.end = syncWithAxis.end;
dateAxis.events.enableType("selectionextremeschanged");
}
}
}
You'll also want to set up each chart's cursor and sync each of them up:
function initCursorListeners() {
cursorShowDisposers = [];
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
var cursor = chart.cursor;
cursor.interactionsEnabled = true;
cursorShowDisposers.push(cursor.events.on("shown", function (event) {
handleShowCursor(event.target);
}));
}
}
var shownCursorChangeDisposer;
var shownCursorZoomStartedDisposer;
var shownCursorZoomEndedDisposer;
function handleShowCursor(shownCursor) {
// disable mouse for all other cursors
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
var cursor = chart.cursor;
if (cursor != shownCursor) {
cursor.interactionsEnabled = false;
}
// remove show listener
cursorShowDisposers[i].dispose();
}
// add change disposer to the hovered chart cursor
shownCursorChangeDisposer = shownCursor.lineX.events.on("positionchanged", function (event) {
syncCursors(shownCursor);
});
shownCursorZoomStartedDisposer = shownCursor.events.on("zoomstarted", function (event) {
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
var cursor = chart.cursor;
if (cursor != event.target) {
var point = { x: event.target.point.x, y: 0 };
cursor.triggerDown(point);
}
}
});
shownCursorZoomEndedDisposer = shownCursor.events.on("zoomended", function (event) {
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
var cursor = chart.cursor;
if (cursor != event.target) {
var point = { x: event.target.point.x, y: 0 };
cursor.triggerUp(point);
}
}
});
shownCursor.events.once("hidden", function (event) {
shownCursorChangeDisposer.dispose();
shownCursorZoomStartedDisposer.dispose();
shownCursorZoomEndedDisposer.dispose();
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
var cursor = chart.cursor;
cursor.hide(0);
cursorShowDisposers[i].dispose();
}
initCursorListeners();
});
}
function syncCursors(syncWithCursor) {
for (var i = 0; i < charts.length; i++) {
var chart = charts[i];
var cursor = chart.cursor;
var point = { x: syncWithCursor.point.x, y: 0 };
if (cursor != syncWithCursor) {
cursor.triggerMove(point);
}
}
}
There are other UI tweaks you can make like disabling the zoom out button on other charts except the top-most one as well as showing the date axis labels on just the last chart.
Here's a full demo on how to do all of this. This is also included in the examples folder in the AmCharts zip file.
If you're using Stock Chart, you might want to hold off.
Stock chart is not yet available for V4. We're planning it for the
second part of 2018. No exact ETA, yet. Sorry.
https://www.amcharts.com/docs/v4/getting-started/migrating-from-v3/#No_Stock_chart_yet
I am using google maps api to create a store locator with clusters and I am referring the marker cluster api.
I wanted to get the list of stores with in a markercluster rather than returning marker cluster with pins/markers. Please find the below code -
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = "";
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
$(mapsCore.mapsVar.totalResults.Result).each(function(k, v) {
$(markers).each(function(km, vm) {
if (parseFloat(v.LAT) == parseFloat(markers[km].position.lat()) && parseFloat(v.LON) == parseFloat(markers[km].position.lng())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.Counter_ID = v.Counter_ID;
x.Counter_Name = v.Counter_Name;
x.Counter_Zip_code = v.Counter_Zip_code;
x.Address_1 = v.Address_1;
x.Address_2 = v.Address_2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.Counter_Tel = v.Counter_Tel;
x.Counter_Email = v.Counter_Email;
x.Open_Time = v.Open_Time;
x.Close_Time = v.Close_Time;
x.LAT = v.LAT;
x.LON = v.LON;
x.MR_FLG = v.MR_FLG;
mapsCore.mapsVar.clusterDetail.Results.push(x);
x = {};
}
});
});
});
As a workaround you can set a custom image to an transparent png and text size to 0, that way it'll be invisible on the map.
cluster.setStyles({
url: your_path/transparent.png,
height: 20,
width: 20,
textSize: 0
});
Alternatively you can try and see if setting the image height and width to 0 works.
All,
thanks for your help for formatting my code and comments any way I found the solution for it. I will attach the spinet of code below
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = '';
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
mapsCore.mapsVar.clusterDetail.Counters.length = 0;
$(mapsCore.mapsVar.totalResults.Counters).each(function(k, v) {
$(markers).each(function(km, vm) {
console.log(parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat()) && parseFloat(v.CounterLongitude) == parseFloat(vm.position.lng()));
if (parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.CounterCode = v.CounterCode;
x.CounterName = v.CounterName;
x.CounterZipCode = v.CounterZipCode;
x.AddressLine1 = v.AddressLine1;
x.AddressLine2 = v.AddressLine2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.CounterPhoneNumber = v.CounterPhoneNumber;
x.CounterEmailAddress = v.CounterEmailAddress;
x.CounterOpenTime = v.CounterOpenTime;
x.CounterCloseTime = v.CounterCloseTime;
x.CounterLatitude = v.CounterLatitude;
x.CounterLongitude = v.CounterLongitude;
x.IsMagicRingAvailable = v.IsMagicRingAvailable;
mapsCore.mapsVar.clusterDetail.Counters.push(x);
x = {};
}
});
});
console.log(mapsCore.mapsVar.clusterDetail);
var template = $.templates("#mapslist");
var output = template.render(mapsCore.mapsVar.clusterDetail);
$(".store-list-section").html(output);
});
Always need to reset the array of object like -
mapsCore.mapsVar.clusterDetail.Counters.length = 0;
This is (again) about array (in my Google map project). After being voteddown, finally I succeed to show multiple markers based on Db data.
I have two PHP pages:
1. inc.php
2. index.php
In inc.php contains values in php array, as follow:
//...... previous code
$googlemap=$result['googlemap'];
$map[] = $googlemap;
}
echo implode(', ' , $map);
The result shows: -5.364000343425874,-150.364000343425874-5.362878747789552,-150.3640003436345874 (this line contains 2 values for example)
To get the values, I use native Ajax:
In index.php contains Javascript codes to fetch the php array (inc.php), extract them into each values for latt and long value, as follow:
Array Values from inc.php is caught by this code:
var wwwsitus = document.querySelector("#valdata").value;
The value inside #valdata grabbed by native ajax:
<script>
function strQuery(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("valdata").value = xmlhttp.responseText;
script_dkill()
}
}
xmlhttp.open("POST", "inc.php?q="+str, true);
xmlhttp.send(null);
}
//start: calling maps
function script_dkill() {
// --- some codes ---
//..........
//}
</script>
Extract #valdata:
var n_result = wwwsitus.split(',');
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
Show the map from this format array:
var wwwsitus = [
['<h4>Universitas Lampung</h4>', x0,y0],
['<h4>Universitas Lampung</h4>', x1,y1]
];
All works 100%.
The problem is:
Values grabbed from database can be 1, 2 or more. (here, I limit the values into 5).
Question:
How do I detect the values in #valdata if #valdata contains 1 or more values so that I can create if for the result???. or, you have other suggestion to handle this.
I hope my question is very clear and pls help me out from this. Thnks.
UPDATED:
What I expect is, for instance:
var wwwsitus = document.querySelector("#valdata").value;
var n_result = wwwsitus.split(',');
if (wwwsitus =null) {
alert('No rent-house found near the place'); // if no value.
// no action
}
else if (wwwsitus =1) {
alert('Found 1 rent-houses'); // if found only 1 value
//continue to show the map based on the value - will show 1 marker.
var x0 = n_result[0];
var y0 = n_result[1];
var wwwsitus = [['<h4>Kost 1</h4>', x0,y0]];
}
else if (wwwsitus =2) {
alert('Found 2 rent-houses'); //if found 2 value
// continue to show the value - will show 2 markers.
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var wwwsitus = [['<h4>Kost 1</h4>', x0,y0],['<h4>Kost 2</h4>', x1,y1]];
}
HOWEVER, the alert() NOT SHOWING the real number of the values as in the Database. How should I code with this.?
This following solution perhaps stupid coding. But it finally works 1000%.
To detect number of values inside #valdata, I add one input field as follow:
<input type='hidden' id='numvalue' value=''/>
Create native Ajax again to grabbed the information about number of values in new file (e.g. num_inc.php)
Here, with that ajax, I will be able to get number of values exist based on mysql query and send to input field #numvalue.
Here's in num_inc.php last code:
$result = $uQuery->fetchColumn();
if($result> 0) {
echo $result; // number of value detected!!!
}
From the process, I finally can extract the data from #valdata and display the map successfully.
Here's the full code:
<script>
//document.getElementById("qfront").addEventListener("keydown", CalmDown, false);
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var datafound = document.getElementById("numvalue").value;
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var wwwsitus = document.getElementById("valdata").value;
var n_result = wwwsitus.split(',');
if (datafound == 1) {
var x0 = n_result[0];
var y0 = n_result[1];
var wwwsitus = [
['<h4></h4>', x0,y0]
];
}
else if (datafound == 2) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1]
];
}
else if (datafound == 3) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var x2 = n_result[4];
var y2 = n_result[5];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1],
['<h4></h4>', x2,y2]
];
}
else if (datafound == 4) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var x2 = n_result[4];
var y2 = n_result[5];
var x3 = n_result[6];
var y3 = n_result[7];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1],
['<h4></h4>', x2,y2],
['<h4></h4>', x3,y3]
];
}
else if (datafound == 5) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var x2 = n_result[4];
var y2 = n_result[5];
var x3 = n_result[6];
var y3 = n_result[7];
var x4 = n_result[8];
var y4 = n_result[9];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1],
['<h4></h4>', x2,y2],
['<h4></h4>', x3,y3],
['<h4></h4>', x4,y4]
];
}
else{
var no_kampus = document.querySelector("#qfront").value;
alert('Data Kost Sekitar Kampus ' + '"'+no_kampus+'"' + ' Belum Terdaftar!');
}
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [
iconURLPrefix + 'red-dot.png',
iconURLPrefix + 'green-dot.png',
iconURLPrefix + 'blue-dot.png',
iconURLPrefix + 'orange-dot.png',
iconURLPrefix + 'purple-dot.png',
iconURLPrefix + 'pink-dot.png',
iconURLPrefix + 'yellow-dot.png'
]
var iconsLength = icons.length;
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-37.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
streetViewControl: true,
panControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_BOTTOM
}
});
var infowindow = new google.maps.InfoWindow({
maxWidth: 160
});
var markers = new Array();
var iconCounter = 0;
// Add the markers and infowindows to the map
for (var i = 0; i < wwwsitus.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(wwwsitus[i][1], wwwsitus[i][2]),
map: map,
animation: google.maps.Animation.DROP,
icon: icons[iconCounter]
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(wwwsitus[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
iconCounter++;
// We only have a limited number of possible icon colors, so we may have to restart the counter
if(iconCounter >= iconsLength) {
iconCounter = 0;
}
}
function autoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].position);
}
// Fit these bounds to the map
map.fitBounds(bounds);
}
autoCenter();
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}
</script>
Input Field:
<input id="qfront" name="qfront" placeholder="Type your campus ..."
value="" type="text" onKeyPress="script_grabbed(this.value);" />
<input id="valdata" name="valdata" type="hidden" value=""/>
<input id="numvalue" name="numvalue" type="hidden" value=""/>
in num_inc.php:
$result = $uQuery->fetchColumn();
if($result> 0) {
echo $result;
}
in inc.php:
$googlemap=$result['googlemap'];
$map[] = $googlemap;
}
echo implode(', ' , $map);
NOTE: If you have another nice solution, please let me know. Of course, I like the better one than I attempt.
Complete Source: Github
I followed the tutorial: http://www.amcharts.com/tutorials/detecting-at-what-value-mouse-pointer-is/
But I don't get the right Value.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Sensor Diagramms</title>
<script src="amcharts/amcharts.js" type="text/javascript"></script>
<script src="amcharts/serial.js" type="text/javascript"></script>
<script src="amcharts/themes/black.js" type="text/javascript"></script>
<!-- amCharts javascript code -->
<script type="text/javascript">
var valueAxis;
var chart;
var chartData = [];
var chartCursor;
var date;
loadCSV("MagnetField.txt");
AmCharts.ready(function(){
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.type = "serial";
chart.pathToImages = "amcharts/images/";
chart.dataProvider = chartData;
chart.categoryField = "date";
chart.dataDateFormat = "DD-MM-YYYY HH:NN:SS.QQQ";
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.minPeriod = "fff";
categoryAxis.parseDates = true;
// CURSOR
chartCursor = new AmCharts.ChartCursor();
chartCursor.categoryBalloonDateFormat= "HH:NN:SS.QQQ";
chartCursor.valueLineEnabled = true;
chartCursor.bulletsEnabled = true;
chartCursor.bulletSize = 2;
chartCursor.oneBalloonOnly = true;
chartCursor.addListener("moved", handleMove);
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chartScrollbar.usePeriod = "fff";
chartScrollbar.autoGridCount = true;
chartScrollbar.color = "#000000";
chart.addChartScrollbar(chartScrollbar);
// GRAPHS
var graph = new AmCharts.AmGraph();
graph.bullet = "round";
graph.title = "x-Axis";
graph.xField = "date";
graph.valueField = "xaxis";
graph.hideBulletsCount = 50;
graph.balloonText = "[[value]] uT";
graph.lineColor = "#b5030d";
chart.addGraph(graph);
var graph2 = new AmCharts.AmGraph();
graph2.bullet = "square";
graph2.title = "y-Axis";
graph2.xField = "date";
graph2.valueField = "xaxis";
graph2.hideBulletsCount = 50;
graph2.balloonText = "[[value]] uT";
graph2.lineColor = "#0352b5";
chart.addGraph(graph2);
var graph3 = new AmCharts.AmGraph();
graph3.bullet = "diamond";
graph3.title = "z-Axis";
graph3.xField = "date";
graph3.valueField = "zaxis";
graph3.hideBulletsCount = 50;
graph3.balloonText = "[[value]] uT";
graph3.lineColor = "#12B500";
chart.addGraph(graph3);
// value Axes
valueAxis = new AmCharts.ValueAxis();
valueAxis.title = "Magnetic Field"
valueAxis.unit = "uT";
chart.addValueAxis(valueAxis);
// Legend
var legend = new AmCharts.AmLegend();
legend.useGraphSettings = true;
legend.align = "center";
legend.valueText = "[[open]]";
chart.addLegend(legend);
chart.titles = [{"id": "Title-1", "size": 15, "text": "Magnetic Sensor"}];
chart.write("chartdiv");
})
function handleMove(event){
var xValue = AmCharts.roundTo(valueAxis.coordinateToValue(event.x - valueAxis.axisX), 2);
//var yValue = AmCharts.formatDate(valueAxis.axisX, "DD/MM/YYYY");
var yValue = event.x - valueAxis.axisX;
console.log("handleMove");
document.getElementById('values').innerHTML = "x:" + xValue + " "+ yValue;
}
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(request.responseText);
}
function parseCSV(data) {
//replace UNIX new lines
data = data.replace (/\r\n/g, "\n");
//replace MAC new lines
data = data.replace (/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// loop through all rows
for (var i = 0; i < rows.length; i++) {
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
// column is array now
// first item is date
date = timeConverter(column[0]);
// second item is value of the second column
var value = column[1].substring(2, column[1].length);
var value2 = column[2].substring(2, column[2].length);
var value3 = column[3].substring(2, column[3].length);
// create object which contains all these items:
var dataObject = {
date: date,
xaxis: value,
yaxis: value2,
zaxis: value3,
Balloon: "Time: "+ date.substring(11,23)
};
// add object to chartData array
chartData.push(dataObject);
}
}
return chartData
}
function setPanSelect() {
if (document.getElementById("rb1").checked) {
chartCursor.pan = false;
chartCursor.zoomable = true;
} else {
chartCursor.pan = true;
}
chart.validateNow();
}
function timeConverter(UNIX_timestamp){
var test = UNIX_timestamp;
var a = new Date(test.substring(0,10)*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = (a.getMonth() + 1) < 10 ? '0' + (a.getMonth() + 1) : (a.getMonth() + 1) ;
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes() < 10 ? '0' + a.getMinutes() : a.getMinutes();
var sec = a.getSeconds() < 10 ? '0' + a.getSeconds() : a.getSeconds();
var msec = test.substring(10,13);
var time = date + "-" + month + "-" + year + " " + hour + ":" + min + ":" + sec + "." + msec;
return time;
}
</script>
</head>
<body>
<div align="center" id="chartdiv" style="margin:auto; width: 80%; height: 500px; background-color: #FFFFFF;" ></div>
<br>
<br>
<div id="values"></div>
</body>
</html>
xValue should be the actual Date on mouseover. But it goes from 1500 to -7188. How do I get the Date or the timestamp? Here is an example of the input data:
1408706279704,x:7.13958740234375,y:-64.31884765625,z:-15.41900634765625
1408706279738,x:7.1990966796875,y:-64.5599365234375,z:-14.51873779296875
1408706279741,x:7.07855224609375,y:-65.27862548828125,z:-13.2598876953125
1408706279760,x:6.95953369140625,y:-65.09857177734375,z:-13.49945068359375
1408706279780,x:6.95953369140625,y:-65.45867919921875,z:-12.4786376953125
1408706279800,x:6.5399169921875,y:-65.45867919921875,z:-12.1795654296875
1408706279821,x:5.7586669921875,y:-65.51971435546875,z:-12.5396728515625
1408706279841,x:6.05926513671875,y:-65.399169921875,z:-13.2598876953125
1408706279861,x:5.7586669921875,y:-65.75927734375,z:-13.13934326171875
1408706279881,x:5.51910400390625,y:-65.9393310546875,z:-12.77923583984375
1408706279902,x:4.91943359375,y:-66.23992919921875,z:-12.41912841796875
1408706279921,x:4.7393798828125,y:-66.53900146484375,z:-11.8194580078125
1408706279941,x:3.95965576171875,y:-66.9586181640625,z:-11.15875244140625
1408706279963,x:3.47900390625,y:-67.19970703125,z:-10.25848388671875
1408706279984,x:3.47900390625,y:-67.3797607421875,z:-9.478759765625
1408706280006,x:3.179931640625,y:-67.7398681640625,z:-8.5784912109375
1408706280024,x:2.9998779296875,y:-67.7398681640625,z:-7.7392578125
$("#chartdiv").mousemove(function () {
var categoryIndex = chart.categoryAxis.xToIndex(event.x));
});
see details here: https://hgminerva.wordpress.com/2014/12/28/how-to-get-the-x-axis-value-of-your-amchart-using-jquery-mousemove-event/
I've a AmSerialChart with three AmGraph on whcih I've formatted the balloonText like this:
grp.balloonText = "<small><b>Date: [[category]]</b></small><br>[[value]]";
The problem with the category (x value) is that is also displayed in the balloonText with the following format: "MMM DD, YYYY". How can I display this date in another way?
I've checked dateFormats in the categoryaxis and dataDateFormat but that only changes the bottom value.
Here's the full code so far:
<script src="amcharts/amcharts.js" type="text/javascript"></script>
<script src="amcharts/serial.js" type="text/javascript"></script>
<script type="text/javascript">
var chart;
var chartData = <% properties.get("jsonData") %>;
var chartTitles = <% properties.get("jsonTitles") %>;
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "amcharts/images/";
chart.dataProvider = chartData;
chart.categoryField = "date";
chart.dataDateFormat = [{period:'fff',format:'JJ:NN:SS'},{period:'ss',format:'JJ:NN:SS'},{period:'mm',format:'JJ:NN:SS'},{period:'hh',format:'JJ:NN:SS'},{period:'DD',format:'JJ:NN:SS'},{period:'WW',format:'JJ:NN:SS'},{period:'MM',format:'JJ:NN:SS'},{period:'YYYY',format:'JJ:NN:SS'}];
// listen for "dataUpdated" event (fired when chart is inited) and call zoomChart method when it happens
// chart.addListener("dataUpdated", zoomChart);
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
categoryAxis.minPeriod = "ss";
categoryAxis.minorGridEnabled = true;
categoryAxis.axisColor = "#DADADA";
// categoryAxis.dateFormats = [{period:'fff',format:'JJ:NN:SS'},{period:'ss',format:'JJ:NN:SS'},{period:'mm',format:'JJ:NN:SS'},{period:'hh',format:'JJ:NN:SS'},{period:'DD',format:'JJ:NN:SS'},{period:'WW',format:'JJ:NN:SS'},{period:'MM',format:'JJ:NN:SS'},{period:'YYYY',format:'JJ:NN:SS'}];
var vAxis = new AmCharts.ValueAxis();
chart.addValueAxis(vAxis);
for (var i = 0; i < chartTitles.length; i++) {
var grp = new AmCharts.AmGraph();
grp.valueField = "d"+i;
grp.title = chartTitles[i];
grp.type = "line";
grp.valueAxis = vAxis; // indicate which axis should be used
grp.lineThickness = 1;
grp.bullet = "round";
grp.labelPosition = "right";
grp.balloonText = "<small><b>Date: [[category]]</b></small><br>[[value]]";
grp.balloonText = "[[value]], [[description]], [[percents]], [[open]], [[total]], [[category]]";
grp.showBalloon = true;
grp.bulletSize = 1;
grp.bulletBorderThickness = 6;
grp.dashLengthField = "dashLength";
chart.addGraph(grp);
}
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chart.addChartScrollbar(chartScrollbar);
// LEGEND
var legend = new AmCharts.AmLegend();
legend.marginLeft = 180;
legend.useGraphSettings = true;
chart.addLegend(legend);
// WRITE
chart.write("chartdiv");
});
</script>
<div id="chartdiv" style="width: 100%; height: 360px;"></div>
Good questions, which helped me to find out that I have a missing property in the docs. In case you don't use ChartCursor, you should use chart.balloonDateFormat property to format the date.