set the right link on each marker - google-maps

I have a map with multiple markers. Everything works fine, but I can't set the links for each marker with click function. It's always the same value.
(p.s. I'm using the gmap3 plugin)
My link information is into json like a .link.link.
$('#search-map-btn').on('click', function () {
$.ajax({
url: "/",
data: $('#dir-search-form').serializeArray(),
type: "POST",
context: document.body
}).done(function (json) {
var mapDiv = $("#map-container");
mapDiv.gmap3({
clear: {}
});
for (key in json) {
var lon = json[key].coords.lon;
var lat = json[key].coords.lat;
var link = json[key].link.link;
//all map parameters
mapDiv = jQuery("#map-container");
mapDiv.height(390).gmap3({
map: {
options: {
"draggable": false,
"mapTypeControl": true,
"mapTypeId": google.maps.MapTypeId.ROADMAP,
"scrollwheel": true,
"panControl": true,
"rotateControl": true,
"scaleControl": true,
"streetViewControl": true,
"zoomControl": true,
"center": [56.9475, 24.106944],
"zoom": 8
}
},
marker: {
values: [{
latLng: [lat, lon]
}],
options: {
"animation": google.maps.Animation.DROP,
"draggable": false,
"clickable": true,
"icon": "<?php bloginfo('template_directory'); ?>/images/new/gmap.marker.png",
},
events: {
click: function () {
document.location.href = json[key].link.link
}
},
},
});
}
});
});

Did that by including cycle before function(key) -> "for(key in json){... })(key);"
$('#search-map-btn').on('click', function(){
$.ajax({
url: "/",
data: $('#dir-search-form').serializeArray() ,
type: "POST",
context: document.body
}).done(function(json){
var mapDiv = $("#map-container");
mapDiv.gmap3({ clear: { } });
for(key in json){
(function(key){
var lon = json[key].coords.lon;
var lat = json[key].coords.lat;
var link = json[key].link;
//all map parameters
mapDiv = jQuery("#map-container");
mapDiv.height(390).gmap3({
map: {
options: {
"draggable": true
,"mapTypeControl": true
,"mapTypeId": google.maps.MapTypeId.ROADMAP
,"scrollwheel": true
,"panControl": true
,"rotateControl": true
,"scaleControl": true
,"streetViewControl": true
,"zoomControl": true
,"center": [56.9475, 24.106944]
,"zoom": 8
}
},
marker:{
values:[
{latLng:[lat, lon], link:[link]}
],
options:{
"animation": google.maps.Animation.DROP,
"draggable": false,
"clickable": true,
"icon": "<?php bloginfo('template_directory'); ?>/images/new/gmap.marker.png",
},
events: {
click: function(){document.location.href = json[key].link.link},
}
});
})(key);

Related

Using Chart JS in Asp.net MVC

I have a table having no of files and their month. i want to show line chart for progress of every month. but i am not able to show the data in the chart,
in console.log date is also not in the required form. how should i put month names which are generated from the sql query on label fields and and every month counting of file on the data
DataSet ds = dbop.GetViews();
List<ListReg> list = new List<ListReg>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
list.Add(new ListReg
{
eFile_registered = Convert.ToInt32(dr["eFile_registered"]),
eFile_Month = Convert.ToDateTime(dr["eFile_Month"]).ToString()
});
}
return Json(list, JsonRequestBehavior.AllowGet);`
//model
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/test/LineChart",
method: 'GET',
dataType: "JSON",
success: function (dr) {
console.log(dr);
var month=dr[0];
var count=dr[1];
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
height: "230px",
width: "300px",
responsive: false,
animation: false,
legend: { position: 'bottom' },
data: {
//labels: ["M", "T", "W", "T", "F", "S", "S"],
labels: month,
datasets: [{
label: 'Monthly Expenses',
data: count,
backgroundColor: "rgb(66, 134, 244)"
}]
}, options: {
events: ['click'],
scaleShowValues: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
autoSkip: false
}
}]
}
}
});
},
"error": function (list) {
alert("Some Error Occured!");
}
});
})

Retrieving JSON data for Highcharts with multiple series and show it in google map infoWindow

I would like to show multiple series of datas in a hightcharts in a google map infowindow.
It works for one serie but I would like to had a second one.
Anybody to help me? MANY THAAANKS!
Here's my code, but it didn't work.
index.php
<script>
var dataSeries=null;
var dataRank=null;
var selectedname="";
$(document).ready(function() {
var locations =
<?php
$query->execute();
echo ("[");
while ($data = $query->fetch()) {
echo("[".$data['hot_webid'].",'".addslashes($data['hot_name'])."',".$data['hot_starrating'].",".$data['hot_latitude'].",".$data['hot_longitude']."],");
}
echo("];");
$query->closeCursor();
?>;
var iw = new google.maps.InfoWindow();
var centerMap = new google.maps.LatLng(0,0);
google.maps.event.addListener(iw,'domready',function(e) {
// Convert date into JS UTC date
for (var k=0; k<dataSeries.length; k++) {
var d=dataSeries[k][0].split(/[- :]/);
dataSeries[k][0]=Date.UTC(d[0], d[1]-1, d[2], d[3], d[4], d[5]);
}
for (var k=0; k<dataRank.length; k++) {
var d=dataRank[k][0].split(/[- :]/);
dataRank[k][0]=Date.UTC(d[0], d[1]-1, d[2], d[3], d[4], d[5]);
}
dataChart = {
chart: {
borderWidth: 2,
renderTo: document.getElementById('container'),
zoomType: 'x',
type:"spline",
lineWidth:0,
height:600,
width:500,
marginRight:40
},
legend: {
enabled: true,
align: 'right',
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderWidth: 0,
layout: 'vertical',
verticalAlign: 'top',
y: 0,
x: -140,
shadow: false,
floating : true
},
rangeSelector: {
enabled: false
},
title: {
text: selectedname
},
subtitle: {
text: 'Prices'
},
legend: {
enabled: true,
align: 'right',
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderWidth: 0,
layout: 'vertical',
verticalAlign: 'top',
y: 0,
x: -140,
shadow: false,
floating : true
},
xAxis: {
title: {
text: 'Date/Time'
}
},
yAxis: [{
title: {
text: 'Rank'
},
height: 200,
lineWidth: 2,
opposite:false
}, {
title: {
text: 'Price'
},
top: 300,
height: 200,
offset: 0,
lineWidth: 2,
opposite:false
}],
navigator: {
enabled: false,
},
credits: {
enabled: false
},
series: [{
name: 'Rank',
color: '#4572A7',
type: 'spline',
yAxis: 0,
marker: {
enabled:true,
radius:2
},
tooltip: {
valueDecimals : 0
},
data: dataRank,
}, {
name: 'Price',
color: '#89A54E',
type: 'spline',
yAxis: 1,
marker: {
enabled:true,
radius:2
},
tooltip: {
valueSuffix: '$',
valueDecimals : 0
},
data: dataSeries,
}]
};
chart = new Highcharts.StockChart(dataChart);
});
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(0.0, 0.0),
mapTypeId : google.maps.MapTypeId.ROADMAP, // Type de carte, diff�rentes valeurs possible HYBRID, ROADMAP, SATELLITE, TERRAIN
streetViewControl: false,
center: centerMap,
panControl: false,
zoomControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var inputLocation = /** #type {HTMLInputElement} */(document.getElementById('search-city'));
// Link it to the UI element.
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(inputLocation);
var autocompleteLocation = new google.maps.places.Autocomplete(inputLocation);
autocompleteLocation.bindTo('bounds', map);
/******************** LISTENER ************************/
google.maps.event.addListener(autocompleteLocation, 'place_changed', function() {
inputLocation.className = '';
var placeStart = autocompleteLocation.getPlace();
if (!placeStart.geometry) {
// Inform the user that the place was not found and return.
inputLocation.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (placeStart.geometry.viewport) {
map.fitBounds(placeStart.geometry.viewport);
} else {
map.setCenter(placeStart.geometry.location);
map.setZoom(13); // Why 13? Because it looks good.
}
var address = '';
if (placeStart.address_components) {
address = [
(placeStart.address_components[0] && placeStart.address_components[0].short_name || ''),
(placeStart.address_components[1] && placeStart.address_components[1].short_name || ''),
(placeStart.address_components[2] && placeStart.address_components[2].short_name || '')
].join(' ');
}
});
/******************** END LISTENER ************************/
var marker, i;
var markers = [];
var contentDiv = '<center><h2>Price and Rank Evolution</h2></center><div id="container" class="info-box"></div>';
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map,
title: locations[i][1]+ " (" + locations[i][2] + " stars)"
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (
function(marker, i) {
return function() {
selectedname = locations[i][1];
stopAnimation(marker);
var requestR = $.ajax({
url: "../ajax/map/get-rank.php",
type: "POST",
dataType: "json",
data: { HotelId: locations[i][0] }
});
var requestS = $.ajax({
url: "../ajax/map/get-prices.php",
type: "POST",
dataType: "json",
data: { HotelId: locations[i][0] }
});
requestR.done(
requestS.done(
function(dataS, dataR, textStatus, jqXHR) {
dataRank=dataR;
dataSeries=dataS;
iw.setContent(contentDiv);
iw.open(map, marker);
}));
requestS.fail(function(jqXHR, textStatus, errorThrown) {});
return false;
}
}
)
(marker, i)
);
}
var markerCluster = new MarkerClusterer(map, markers);
google.maps.event.addListener(iw, 'closeclick', function() {});
function stopAnimation(marker) {
setTimeout(function () {
marker.setAnimation(null);
}, 3000);
}
});
</script>
And my JSON php files
<?php
header("Content-type: application/json");
include('../../db.php');
if (isset($_POST['HotelId'])) $res_idHotel=$_POST['HotelId'];
$query = $bdd->prepare("SELECT res_date, res_price ".
"FROM exp_result ".
"WHERE res_idHotel = $res_idHotel ".
"AND res_date ".
//"BETWEEN DATE( DATE_SUB( NOW() , INTERVAL 7 DAY ) ) ".
//"AND DATE ( NOW() ) ".
"GROUP BY res_date ORDER BY res_date;");
$query->execute();
$data = $query->fetch();
if ($data) {
echo "[ ";
do {
echo "[ \"".$data['res_date']."\", ".$data['res_price']." ]";
$data = $query->fetch();
if ($data) echo ",";
} while ($data);
echo "]";
} else {
echo "[]";
}
$query->closeCursor();
?>
and
<?php
header("Content-type: application/json");
include('../../db.php');
if (isset($_POST['HotelId'])) $res_idHotel=$_POST['HotelId'];
$query = $bdd->prepare("SELECT res_date, res_rank ".
"FROM exp_result ".
"WHERE res_idHotel = $res_idHotel ".
"AND res_date ".
//"BETWEEN DATE( DATE_SUB( NOW() , INTERVAL 7 DAY ) ) ".
//"AND DATE ( NOW() ) ".
"GROUP BY res_date ORDER BY res_date;");
$query->execute();
$dataR = $query->fetch();
if ($dataR) {
echo "[ ";
do {
echo "[ \"".$dataR['res_date']."\", ".$dataR['res_rank']." ]";
$dataR = $query->fetch();
if ($dataR) echo ",";
} while ($dataR);
echo "]";
} else {
echo "[]";
}
$query->closeCursor();
?>

completely destroy marker on gmap3

I am trying to let a user drop up to 10 markers and remove them onClick. I also have it updating a "div" with the coordinates of the markers on the map when a user adds a marker or drags. I have everything working except for when the user deletes a marker, it's still seems to be on the map when I loop through the markers. Any idea what I'm doing wrong?
jsFiddle: jsfiddle.net/ryanverdel/WRyrJ/
Code:
$(document).ready(function () {
var markerCount = 0;
$("#test1").gmap3({
map: {
options: {
center: [-2.2214281090541204, -78.695068359375],
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
disableDoubleClickZoom: true,
streetViewControl: false,
},
events: {
click: function (map, event) {
if(markerCount < 10){
$(this).gmap3(
{
marker: {
latLng: event.latLng,
options:{
draggable: true,
animation: google.maps.Animation.DROP,
},
events: {
click: function(marker) {
marker.setMap(map);
marker.setMap(null);
marker = null;
delete marker;
console.log(marker);
markerCount--;
},
dragend: function(marker) {
$("#inputArray").empty();
setTimeout(function(){
var markers = $("#test1").gmap3({
get: {
all: true
}
});
$.each(markers, function(i, marker){
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() +', '+ '"longitude":' + marker.position.lng() +'},'+'</p>');
});
}, 400);
}
},
},
});
markerCount++;
$("#inputArray").empty();
setTimeout(function(){
var markers = $("#test1").gmap3({
get: {
all: true
}
});
$.each(markers, function(i, marker){
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() +', '+ '"longitude":' + marker.position.lng() +'},'+'</p>');
});
}, 400);
}
else{
return false;
};
}
}
}
});
});
This sort of thing is maybe less than straightforward in gmap3. You need a slightly different mindset compared with that required for the direct google.maps API.
Thee main poitns :
You need to provide the markers with an id, name or tag
You need to remove the marker with clear
You need to make judicious use of callbacks (the gmap3 way).
Here's your code unravelled into a set of functions, with the necessary fixes applied
$(document).ready(function () {
var mapOpts = {
center: [-2.2214281090541204, -78.695068359375],
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
disableDoubleClickZoom: true,
streetViewControl: false,
};
function genId() {
return '' + (new Date()).getTime();
}
function addMarker(map, event) {
if (markerCount < 10) {
var uid = genId();
$(this).gmap3({
marker: {
latLng: event.latLng,
options: {
draggable: true,
animation: google.maps.Animation.DROP
},
events: {
click: function() {
clearMarker(uid);
},
dragend: listMarkers
},
id: uid
}
});
markerCount++;
listMarkers();
} else {
return false;
};
}
function listMarkers() {
$("#test1").gmap3({
get: {
all: true,
callback: function(results) {
$("#inputArray").empty();
$.each(results, function (i, marker) {
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() + ', ' + '"longitude":' + marker.position.lng() + '},' + '</p>');
});
}
}
});
}
function clearMarker(uid) {
$('#test1').gmap3({
clear: {
id: uid,
callback: function() {
listMarkers();
markerCount--;
}
}
});
}
var markerCount = 0;
$("#test1").gmap3({
map: {
options: mapOpts,
events: {
click: addMarker
}
}
});
});
DEMO

JQGrid data not being displayed

I have this code for my jqrid. But the data is not getting displayed in grid. The grids gets generated but no data is being shown in the grid. Also I have applied error control but that gives me no error. The code is as follows:
$(document).ready(function () {
'use strict';
var expHeadVal = "12345:Party;12346:Miscellaneous;12347:Conveyance;12348:Staff Welfare";
var webForm = document.forms[0];
var i = 0;
var mydata = "";
var jsonData = {
"records": "4",
"userData":{
},
"rows":[
{"id":"1", "sdate":"2013-03-22","expHead":"Party","expAmt":"1000","expReason":"Yes","expRemark":"FedEx"},
{"id":"2", "sdate":"2013-03-21","expHead":"Conveyance","expAmt":"200","expReason":"Yes","expRemark":"FedEx"},
{"id":"3", "sdate":"2013-03-20","expHead":"Conveyance","expAmt":"165","expReason":"Yes","expRemark":"FedEx"},
{"id":"4", "sdate":"2013-03-11","expHead":"Staff Welfare","expAmt":"1653","expReason":"Yes","expRemark":"FeEx"}
]
}
// alert (jsonData.rows[3].id);
var $grid = $("#View1"),
initDateWithButton = function (elem) {
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
showWeek: true,
showButtonPanel: true,
onClose: function (dateText, inst) {
inst.input.focus();
}
});
$(elem).next('button.ui-datepicker-trigger').button({
text: false,
icons: {primary: 'ui-icon-calculator'}
}).find('span.ui-button-text').css('padding', '0.1em');
}, 100);
},
numberTemplate = {
formatter: 'number',
align: 'right',
sorttype: 'number',
editable: true,
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'] }},
dateTemplate = {
align: 'center',
sorttype: 'date',
editable: true,
formatter: 'date',
formatoptions: { newformat: 'd-M-Y' },
datefmt: 'd-M-Y',
editoptions: { dataInit: initDateWithButton, size: 11 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton,
size: 11, // for the advanced searching dialog
attr: {size: 11} // for the searching toolbar
}
},
lastSel;
$grid.jqGrid({
datatype: "local",
data: jsonData,
jsonReader : {
// userdata: "userData",
root: "rows",
repeatitems: false,
// id: "1",
records: "records"
},
// data: jsonData,
colNames: ['Date','Expense Head','Amount', 'Reason','Remarks'],
colModel: [
// {name:'id', index:'id', width:15, editable:false, key: true, hidden: true},
{name:'sdate', index:'sdate', width:200, template: dateTemplate },
{name:'expHead', index:'expHead', width:150, editable:true, sorttype:'number',sortable:true, edittype:"select", editoptions:{value:expHeadVal}},
{name:'expAmt', index:'expAmt', width:100, editable:true, template: numberTemplate, summaryType:'sum' },
{name:'expReason', index:'expReason', width:200, editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}},
{name:'expRemark', index:'expRemark', width:200,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}}],
loadtext: "Loading...",
sortname: ['Col0','Col1'],
pager: '#pView1',
caption: "Expense Table",
gridview: true,
rownumbers: true,
autoencode: true,
ignoreCase: true,
viewrecords: true,
sortorder: 'desc',
height: '100%',
editurl: 'clientArray',
beforeSelectRow: function (rowid) {
if (rowid !== lastSel) {
$(this).jqGrid('restoreRow', lastSel);
lastSel = rowid;
}
return true;
},
ondblClickRow: function (rowid, iRow, iCol, e) {
var p = this.p, $this = $(this);
// if the row are still non-selected
if ((p.multiselect && $.inArray(rowid, p.selarrrow) < 0) || rowid !== p.selrow)
{ $this.jqGrid("setSelection", rowid, true); }
$this.jqGrid('editRow', rowid, true, function () {
if (e.target.disabled)
{ e.target.disabled = false; }
$("input, select", e.target).focus();
});
return;
},
loadComplete: function () {
alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
$grid.jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
$grid.jqGrid('navGrid', '#pView1', {refreshstate: 'current', edit: false, add: false, del: false});
$grid.jqGrid('inlineNav',"#pView1");
});
Can anybody tell me what is missing here?
Thanks for your help in advance.
Siddhartha
You should change data: jsonData to data: jsonData.rows because you use datatype: "local".
By the way jsonReader option will not used in case of datatype: "local". The format of data in jsonData.rows already corresponds default format of input data for datatype: "local". If you do will need to fill jqGrid having datatype: "local" with another format of data you should use localReader option instead of jsonReader (see the documentation).

Sencha Touch 2: Google Maps Directions Route won't show

I'm using a view to show a location on a map with a small form below it to grab the users address if they want directions. The map renders initially as I want. There is a controller to handle tapping the button and updating the display with the route. I can see that it is successfully retrieving the route information. It's just not updating the display to show it. What am I missing?
Here's the view:
var tcmlatlng = new google.maps.LatLng(38.898748, -77.037684);
Ext.define('VisitTCMIndy.view.Directions',{
extend: 'Ext.Panel',
requires: [
'Ext.form.Panel',
'Ext.Map'
],
config: {
layout: 'vbox',
items: [
{
xtype: 'map',
useCurrentLocation: false,
flex: 3,
mapOptions: {
center: tcmlatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
listeners: {
maprender: function(map,gmap,options){
var homemarker = new google.maps.Marker({
position: tcmlatlng,
map: gmap
});
}
}
},
{
xtype: 'formpanel',
id: 'directionsform',
flex: 1,
items:[
{
xtype: 'textfield',
name: 'address',
label: 'Address',
},
{
xtype: 'button',
ui:'action',
text: 'Get Directions'
}
]
}
]
}
});
Here's the controller
Ext.define('VisitTCMIndy.controller.Directions',{
extend: 'Ext.app.Controller',
config: {
control: {
dButton: {
tap: 'loaddirections'
}
},
refs: {
dButton: '#directionsform button[ui=action]',
tcmmap:'map',
addfield:'textfield[name=address]'
}
},
loaddirections: function(dbutton){
console.log('loaddirections');
var gmap = this.getTcmmap();
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(gmap.map);
var tcmadd = "1600 Pennsylvania Ave, Washington, DC";
var originadd = this.getAddfield().getValue();
var request = {
origin: originadd,
destination: tcmadd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status){
console.log(status);
if(status = google.maps.DirectionsStatus.OK){
console.log(result);
directionsDisplay.setDirections(result);
}
});
}
});
I was referencing the map incorrectly. I was trying to reference it directly instead of using the getter. So anywhere you see 'gmap.map' it should read 'gmap.getMap()'.