I have names of 1100 hospitals from NY region. I need to find the address of these hospitals from google. I am looking for some script which I can use to supply all these hospital name and it could return me with an address. The script could return a simple google search result.
Input format:
Hospital Name
Center for Ambulatory Surgery
Genetic Diagnostic Labs Inc
Desired output format:
Hospital Name Hospital Address
Center for Ambulatory Surgery 3112 Sheridan Dr, Amherst, NY 14226
Genetic Diagnostic Labs Inc 490 Delaware Ave, Buffalo, NY 14202
A solution with google Places API, but the results may be not very accurate:
http://codepen.io/anon/pen/JogeyV?editors=101
var NY_latlng = new google.maps.LatLng(40.828624, -73.898605);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: NY_latlng,
zoom: 15
});
var hospitals = [];
var hospitals_names = ["Center for Ambulatory Surgery","Genetic Diagnostic Labs Inc"];//insert your full list here
var service = new google.maps.places.PlacesService(map);
hospitals_names.forEach( function(name ){
service.textSearch(
{
query: name,
location: NY_latlng,
radius: 50000, //in meter
},function(results,status){
if (status == google.maps.places.PlacesServiceStatus.OK){
var hospital= { name: name, addresses: []};
$('#address-list').append("<h2>"+name+"</h2><ul></ul>");
for (var i = 0; i < results.length; i++) {
hospital.addresses.push( results[i].formatted_address );
$('#address-list > ul').append("<li>"+results[i].formatted_address);
}
hospitals.push( hospital );
}
});
You can do this in R with the ggmap package, though perhaps not reliably enough to produce the results you want. For instance this attempt to geocode fails:
geocode("Genetic Diagnostic Labs Inc")
Warning message:
geocode failed with status ZERO_RESULTS, location = "Genetic Diagnostic Labs Inc"
So to illustrate a solution, I appended " NY" to the Google searches:
library(ggmap)
hospital_names <- c("Center for Ambulatory Surgery", "Genetic Diagnostic Labs Inc")
address_vec <- lapply(hospital_names, function(x) revgeocode(as.numeric(geocode(paste(x,", NY")))))
result <- data.frame(name = hospital_names, address = unlist(address_vec))
Result:
result
name address
1 Center for Ambulatory Surgery 426 Union Road, West Seneca, NY 14224, USA
2 Genetic Diagnostic Labs Inc City Hall Park Path, New York, NY 10007, USA
But these are not the addresses you specified - you may need to refine your inputs.
Related
I would like retrieving data from nested href from jsoup, i mean:
i have href:
https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999
and i want to take each data from this 10 fighers, e.g.:
1.
STIPE MIOCIC
AGE: 37
or
ASSOCIATION:
STRONG STYLE FIGHT TEAM
2.
DANIEL CORMIER
AGE: 40
or
ASSOCIATION:
AMERICAN KICKBOXING ACADEMY
etc..
How to do this?
String url = "https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999";
Document document = Jsoup.connect(url).get();
Elements allH1 = document.select("h2");
for (Element href : allH1) {
Elements allAge = document.select("div.birth_info");
for (Element age : allAge) {
System.out.println(href.select("a[href]").text().toString());
System.out.println(age.select() // something there?);
}
The data you are looking for is present on seperate pages - each fighter has his own page, so you must crawl all the pages one by one to get the data.
First you have to get the link for each page, with the selector h2 > a[href]:
String url = "https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999";
Document document = Jsoup.connect(url).get();
Elements fighters = document.select("h2 > a[href]");
for (Element fighter : fighters) {
System.out.println(fighter.text() + " " + fighter.attr("href"));
}
After that, you can load each page and extract the data:
String fighterUrl = "https://www.sherdog.com" + fighter.attr("href");
Document doc = Jsoup.connect(fighterUrl).get();
Element fighterData = doc.select("div.data").first();
System.out.println(fighterData.text());
Combined together, you get:
String url = "https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999";
Document document = Jsoup.connect(url).get();
Elements fighters = document.select("h2 > a[href]");
for (Element fighter : fighters) {
System.out.println(fighter.text());
String fighterUrl = "https://www.sherdog.com" + fighter.attr("href");
Document doc = Jsoup.connect(fighterUrl).get();
Element fighterData = doc.select("div.data").first();
System.out.println(fighterData.text());
System.out.println("---------------");
}
And the (partial) output is:
Stipe Miocic
Born: 1982-08-19 AGE: 37 Independence, Ohio United States Height 6'4" 193.04 cm Weight 245 lbs 111.13 kg Association: Strong Style Fight Team Class: Heavyweight Wins 19 15 KO/TKO (79%) 0 SUBMISSIONS (0%) 4 DECISIONS (21%) Losses 3 2 KO/TKO (67%) 0 SUBMISSIONS (0%) 1 DECISIONS (33%)
Daniel Cormier
Born: 1979-03-20 AGE: 40 San Jose, California United States Height 5'11" 180.34 cm Weight 251 lbs 113.85 kg Association: American Kickboxing Academy Class: Heavyweight Wins 22 10 KO/TKO (45%) 5 SUBMISSIONS (23%) 7 DECISIONS (32%) Losses 2 1 KO/TKO (50%) 0 SUBMISSIONS (0%) 1 DECISIONS (50%) N/C 1
If you want to get the age, association and so as seperate fields, you'll have to extract them with regex.
I'm making an App for Android 6.0 and I want to use the new class NetworkStatsManager for getting mobile data usage.
I added all permission I need in manifest and require the permission runtime.
When I call the method:
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI, "", fromDate.getTime(), toDate.getTime());
return the right value for WIFI usage.
But if i replace TYPE_WIFI with TYPE_MOBILE the result is always 0.
NetworkStats.Bucket bucket = null;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, "", fromDate.getTime(), toDate.getTime());
if(bucket == null){
Log.i("Info", "Error");
}else{
Log.i("Info", "Total: " + (bucket.getRxBytes() + bucket.getTxBytes()));
}
} catch (RemoteException e) {
e.printStackTrace();
}
I found a solution of this problem with hidden APIs (android statistic 3g traffic for each APP, how?) and when trying to retrieve mobile data usage information with TYPE_MOBILE was necessary to inform the SubscriberID, unlike when I tryed to get information TYPE WIFI.
Try this code
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String subscriberID = tm.getSubscriberId();
NetworkStats networkStatsByApp = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_MOBILE, subscriberID, start, end, uid);
So when you are using TYPE_MOBILE, it's necessary to you use a valid subscriberID.
As a follow up to the accepted answer, I would also like to point out that in the following code,
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String subscriberID = tm.getSubscriberId(); //subscriberID is usually the IMSI number (for GSM phones)
TelephonyManager tm contains the information about the default telephony service (SIM card) that is being used for making calls. So, if you are using a phone with Dual SIM cards and SIM 1 is being used for calls and SIM 2 is being used for Data, then TelephonyManager tm will hold information about SIM 1 and in your use case, where you are using NetworkStatsManager for getting Data usage stats, SIM 1 info will be of no use as it is not being used for consuming Data. So, you somehow need to fetch the TelephonyManager for SIM 2 so that you can use the correct subscriber Id of SIM 2 in networkStatsManager.querySummaryForDevice() to get the mobile data usage stats. So, how do you do this?
One way that I figured out is like this:
public void subscriberIdsOfDualSim(){
SubscriptionManager subscriptionManager = SubscriptionManager.from(this);
//we'll now get a List of information of active SIM cards
//for example, if there are 2 SIM slots and both the slots have 1 SIM card each, then the List size will be 2
List<SubscriptionInfo> activeSubscriptionInfoList = subscriptionManager.getActiveSubscriptionInfoList();
TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
for (SubscriptionInfo subscriptionInfo : activeSubscriptionInfoList) {
//loop through the SIM card info
//if there are 2 SIM cards, then we'll try to print the subscriberId of each of the SIM cards
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
//the following createForSubscriptionId() is available from API 24 :(
TelephonyManager manager1=manager.createForSubscriptionId(subscriptionInfo.getSubscriptionId());
String operatorName=manager1.getNetworkOperatorName();
String subscriberId=manager1.getSubscriberId(); //use this subscriberId to do NetworkStatsManager stuff
System.out.println("subscriberIdsOfDualSim: Carrier Name: "+operatorName+", subscriber id: "+subscriberId);
}
}
}
Notice that I have used createForSubscriptionId() method. One limitation of this method is that it can be used from API 24 (Android 7.0 Nougat) only.
So, if you are using both SIM 1 and SIM 2 for data consumption, then you can get the data usage info for each of the SIM cards by providing the subscriberId of each of them to networkStatsManager.querySummaryForDevice(). But, if you want to get correct mobile data consumption (both SIM 1 and SIM 2 inclusive) and you want to support phones below Nougat, then the good old getMobileRxBytes() and getMobileTxBytes() methods in TrafficStats class is what you may have to use.
Another follow up to the accepted answer and #Nandan, it's possible to obtain subscriber ids of both SIM cards using below code
SubscriptionManager subman = (SubscriptionManager)getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE);
TelephonyManager telman = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
List<SubscriptionInfo> li = subman.getActiveSubscriptionInfoList();
for(SubscriptionInfo info : li){
int sid = info.getSubscriptionId(); //not the id we want
try{
Class c = Class.forName("android.telephony.TelephonyManager");
Method m = c.getMethod("getSubscriberId", new Class[]{int.class});
Object o = m.invoke(telman, new Object[]{sid});
String subid = (String)o; //id we want
Log.i("SubscriptionId", subid);
}
catch(Exception e){}
}
Credit to answer link https://stackoverflow.com/a/38071705/9038181
I've gone through multiple posts about parsing and such. Most of the responses that I saw were recommending the person to use a Library or something else. My problem right now is creating an algorithm that will fetch the exact information I want. My purpose for this is to fetch 2 statuses from the Weather website for school closings. I started using Jsoup as someone recommended but I need help with it.
Webpage: Click here
Image: Click here
Example of webpage source: click here
I could probably figure out how to get a certain line of text within the webpage since I already know the name of the school im looking for, but 2 lines down is the status which is what I need. would be easy if each school had a certain status but they are all either Closed or Two-hour Delay so I can't just make a search for that. I want some ideas or answers on how i can apporach this. I am going to do this 2 times because I am wanting to look up 2 schools. I already have the names which I can use to look them up I just need the status.
Here is an example of what I want to do. (sudo code)
Document doc = connect(to url);
Element schoolName1 = doc.lookForText(htmlLineHere/schoolname);
String status1 = schoolName.getNext().text();//suppose this gets the line right after which should be my status and then cleans off the Html.
This is what I have right now
public static SchoolClosing lookupDebug() throws IOException {
final ArrayList<String> Status = new ArrayList<String>();
try {
//connects to my wanted website
Document doc = Jsoup.connect("http://www.10tv.com/content/sections/weather/closings.html").get();
//selects/fetches the line of code I want
Element schoolName = doc.html("<td valign="+"top"+">Athens City Schools</td>");
//an array of Strings where I am going to add the text I need when I get it
final ArrayList<String> temp = new ArrayList<String>();
//checking if its fetching the text
System.out.println(schoolName.text());
//add the text to the array
temp.add(schoolName.text());
for (int i = 0; i <= 1; i++) {
final String[] tempStatus = temp.get(i).split(" ");
Status.add(tempStatus[0]);
}
} catch (final IOException e) {
throw new IOException("There was a problem loading School Closing Status");
}
return new SchoolClosing(Status);
}
Document doc = Jsoup.connect(
"http://www.10tv.com/content/sections/weather/closings.html")
.get();
for (Element tr : doc.select("#closings tr")) {
Element tds = tr.select("td").first();
if (tds != null) {
String county = tr.select("td:eq(0)").text();
String schoolName = tr.select("td:eq(1)").text();
String status = tr.select("td:eq(2)").text();
System.out.println(String.format(
"county: %s, schoolName: %s, status: %s", county,
schoolName, status));
}
}
output:
county: Athens, schoolName: Beacon School, status: Two-hour Delay
county: Franklin, schoolName: City of Grandview Heights, status: Snow Emergency through 8pm Thursday
county: Franklin, schoolName: Electrical Trades Center, status: All Evening Activities Cancelled
county: Franklin, schoolName: Hilock Fellowship Church, status: PM Services Cancelled
county: Franklin, schoolName: International Christian Center, status: All Evening Activities Cancelled
county: Franklin, schoolName: Maranatha Baptist Church, status: PM Services Cancelled
county: Franklin, schoolName: Masters Commission New Covenant Church, status: Bible Study Cancelled
county: Franklin, schoolName: New Life Christian Fellowship, status: All Activities Cancelled
county: Franklin, schoolName: The Epilepsy Foundation of Central Ohio, status: All Evening Activities Cancelled
county: Franklin, schoolName: Washington Ave United Methodist Church, status: All Evening Activities Cancelled
or in a loop:
for (Element tr : doc.select("#closings tr")) {
System.out.println("----------------------");
for (Element td : tr.select("td")) {
System.out.println(td.text());
}
}
that gives:
----------------------
Athens
Beacon School
Two-hour Delay
----------------------
Franklin
City of Grandview Heights
Snow Emergency through 8pm Thursday
----------------------
Franklin
Electrical Trades Center
All Evening Activities Cancelled
...
I have a json which has a number of nested JSONARRAY. here is the snippet.
{
"location": [
{
"name": "Perth",
"conferencelocation": [
{
"locationname":"Stage 1" ,
"guests": [
{
"guestid":"4074513426041094",
"guestname":"Keegan Connor Tracy",
"time":"9am",
"largeimg":"http://ozcomiccon.com/images/banner/Keegan.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/Keeganresized.jpg",
"biotext": "Born in Windsor, Ontario, Canada, Tracy attended Wilfrid Laurier University in Waterloo, Ontario, Canada, where she orginally studied business. She later switched to psychology. She spent a year in Europe working in Dublin, Paris and Nice, where she was supposed to be completing her 4th year of study. She later returned to WLU to finish her degree. She moved to Vancouver, B.C. where she has had all of her acting jobs.",
"autographs":"$30 each (an 8x10 photograph will be included with each signature, or you may choose to have an appropriate personal item signed).",
"photographs":"Photo with Keegan $40.",
"genre":"acting",
"links": [
{"linkname":"Twitter", "url":"https://twitter.com/keegolicious" },
{"linkname":"IMDB", "url":"http://www.imdb.com/name/nm0870535/" }
]
},
{
"guestid":"1054713366041913",
"guestname":"Matthew Clark",
"time":"10am",
"largeimg":"http://ozcomiccon.com/images/banner/matthewclark.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/matthewclarkresized.jpg",
"biotext": "Matthew Clark is a comic book artist living and working in Portland, Oregon. Having worked on art of some of the most well-known DC characters in comic book history, he recently did pencils for DC’s latest version of the Doom Patrol. Matthew is currently working on Ghost Rider for Marvel Comics, with whom he has signed an exclusive two-year deal.<br /><br />Matthew has lived in Portland for the past 13 years, just above an art gallery in the heart of downtown. He loves to walk around this fair city (mainly because he sold his car and needed to force himself to exercise). He’s a native Oregonian and that’s saying something. For the past 11 years he’s met Greg Rucka for coffee every Wednesday pretty much without fail at the same place (we pretty much carved our names in the table). Matthew was also one of the original founders of Mercury Studio (now Periscope Studio); he got his start at Studiosaurus.<br /><br />He still reads comics, loves what he does, and works very hard. Loves to meet new people, but is really quiet (and has great hair).",
"autographs":"Complimentary at guest's discretion.(Twitter)",
"photographs":"",
"genre":"comic",
"links": [
{"linkname":"Website", "url":"http://www.matthewclarkartist.com/" },
{"linkname":"Twitter", "url":"https://twitter.com/emceeartist" }
]
}
]
},
{
"locationname":"Stage 2" ,
"guests": [
{
"guestid":"106146633306036834",
"guestname":"Sean Williams",
"time":"8am",
"largeimg":"http://ozcomiccon.com/images/banner/seanwilliams.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/seanwilliamsresized.jpg",
"biotext": "Sean Williams was born in the dry, flat lands of South Australia, where he still lives with his wife and family. He has been called many things in his time, including “the premier Australian speculative fiction writer of the age†(Aurealis), the “Emperor of Sci-Fi†(Adelaide Advertiser), and the “King of Chameleons†(Australian Book Review) for the diversity of his output. That award-winning output includes thirty-five novels for readers all ages, seventy-five short stories across numerous genres, the odd published poem, and even a sci-fi musical.<br /><br />He is a multiple recipient of the Aurealis and Ditmar Awards in multiple categories and has been nominated for the Philip K. Dick Award, the Seiun Award, and the William Atheling Jr. Award for criticism. He received the “SA Great†Literature Award in 2000 and the Peter McNamara Award for contributions to Australian speculative fiction in 2008.<br /><br />On the sci-fi front, he is best-known internationally for his original award-winning space opera series as well as several novels set in the Star Wars universe, many co-written with fellow-Adelaidean Shane Dix. These include the Astropolis, Evergence, Orphans and Geodesica series, and the computer game tie-in The Force Unleashed–the first such adaptation ever to debut at #1 on the New York Times bestseller list. A series for young readers, The Fixers, pitted an increasingly lost protagonist against zombies, cyborgs, and vampires across numerous universes. His most recent releases in the Star Wars universe are The Old Republic: Fatal Alliance and The Force Unleashed II.",
"autographs":"Complimentary at guest's discretion.",
"photographs":"",
"genre":"comic",
"links": [
{"linkname":"website", "url":"http://www.seanwilliams.com" }
]
},
{
"guestid":"17148603639603876",
"guestname":"Richard Dean Anderson",
"time":"10am",
"largeimg":"http://ozcomiccon.com/images/banner/richarddeananderson.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/richarddeanandersonresized.jpg",
"biotext": "Richard Dean Anderson is probably best known as MacGyver, the clever and inventive nonviolent hero who solved problems in his own unique way for seven successful seasons on ABC. In his roles before and since, this gifted actor has continued to demonstrate his remarkable talent and versatility.<br /><br />Richard was born on January 23, 1950 in Minneapolis, Minnesota. His father, Stuart Anderson, taught English, drama, and humanities at a local high school, and is an accomplished jazz bassist. His mother, Jocelyn, is an artist, talented in both painting and sculpture. Richard is the eldest of four sons. He and his brothers, Jeffrey Scott, Thomas John, and James Stuart, grew up in the Minneapolis suburb of Roseville, where Richard developed early interests in sports, the arts, music, and acting.<br /><br />Like many boys growing up in Minnesota, Richard dreamed of becoming a professional hockey player. However, at the age of 16, he broke both arms, in separate accidents three weeks apart, while playing in high school hockey games. He put aside his dreams of playing professionally, though he still harbors a deep love for the sport. Richard talks of his restlessness growing up, his early desire to explore, and his adventures hitchhiking and hopping freight trains. At the age of 17, he took a 5641 mile bicycle trip from his home in Minnesota through Canada and Alaska, an experience which was sparked by his sense of adventure and discovery, but which also gave him a more centered sense of direction.",
"autographs":"Autograph from Richard $50.",
"photographs":"Photograph with Richard $80. SG1 double shot with Richard and Teryl Rothery $150. SG1 triple shot with Richard, Teryl Rothery and Corin Nemec $200.",
"genre":"acting",
"links": [
{"linkname":"Website", "url":"http://www.rdanderson.com/" },
{"linkname":"Twitter", "url":"https://twitter.com/andersonrdean" }
]
}
]
}
]
}
]
I have object class named Name, and I want to put all the data of the name(perth) jsonobject as a single object of the Name class. But it is not adding data in the arraylist correctly, more clearly the guestid, guestname etc tag values are being saved but overwrites the previous one. Here is my parsing code:
public ArrayList<Guest> parseInitiator() throws ClientProtocolException,
IOException, JSONException {
InputStream is = new FileInputStream(new File(Url));
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String mResponse = new String(buffer);
JSONObject first = new JSONObject(mResponse);
JSONArray firstarray = first.getJSONArray("location");
ArrayList<Guest> parsedData = new ArrayList<Guest>();
for (int i = 0; i < firstarray.length(); i++) {
JSONObject jonj = firstarray.getJSONObject(i);
name = jonj.getString("name");
JSONArray confarray = jonj.getJSONArray("conferencelocation");
locationname = new String[confarray.length()];
for (int j = 0; j < confarray.length(); j++) {
JSONObject conobbj = confarray.getJSONObject(j);
locationname[j] = conobbj.getString("locationname");
JSONArray guestarray = conobbj.getJSONArray("guests");
guestid= new String[guestarray.length()];
guestname= new String[guestarray.length()];
time= new String[guestarray.length()];
largeimg= new String[guestarray.length()];
smallimg= new String[guestarray.length()];
biotext= new String[guestarray.length()];
autographs= new String[guestarray.length()];
photographs= new String[guestarray.length()];
genre= new String[guestarray.length()];
for (int k = 0; k < guestarray.length(); k++) {
JSONObject guestobbj = guestarray.getJSONObject(k);
guestid[k] = guestobbj.getString("guestid");
guestname[k] = guestobbj.getString("guestname");
time[k] = guestobbj.getString("time");
largeimg[k] = guestobbj.getString("largeimg");
smallimg[k] = guestobbj.getString("smallimg");
biotext[k] = guestobbj.getString("biotext");
autographs[k] = guestobbj.getString("autographs");
photographs[k] = guestobbj.getString("photographs");
genre[k] = guestobbj.getString("genre");
JSONArray linkar = guestobbj.getJSONArray("links");
arlink= new String[linkar.length()];
arurl= new String[linkar.length()];
for (int l = 0; l < linkar.length(); l++) {
JSONObject linkobj = linkar.getJSONObject(l);
arlink[l] = linkobj.getString("linkname");
arurl[l] = linkobj.getString("url");
}
}
}
parsedData.add(new Guest(name,locationname, guestid, guestname, time, largeimg, smallimg, biotext,
autographs, photographs, genre,arlink, arurl));
}
return parsedData;
}
Can anyone make me clear about the mistake I have made?
So here is my solution:
JSONObject first = new JSONObject(mResponse);
JSONArray locArr = first.getJSONArray("location"); // contains one object
JSONObject locArrObj = locArr.getJSONObject(0); // cotains one "out" array
JSONArray conferenceLocArr = locArrObj.getJSONArray("conferencelocation");
// this array has two objects and each object has array
JSONObject o = null;
JSONArray arr = null;
for (int i = 0; i < conferenceLocArr.length(); i++) {
o = conferenceLocArr.getJSONObject(i); // it has one array
arr = o.getJSONArray("guests");
// do your work with Stage 1 and guests
// and for second object for Stage 2 and guests.
}
I am using jQuery for UI and my programming language is Java. Now I want to get remote data using an Ajax call to Java servlet and get the records from remote site in sorted order with also grand total. How can I do that?
I found many examples, but that was in PHP only. I want to implement it in Java, and I am not able to understand PHP.
Example which I found is as below.
JavaScript code
jQuery("#48remote2").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55, editable:true, sorttype:'int',summaryType:'count', summaryTpl : '({0}) total'},
{name:'invdate',index:'invdate', width:90, sorttype:'date', formatter:'date', datefmt:'d/m/Y'},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right", sorttype:'number',formatter:'number',summaryType:'sum'},
{name:'tax',index:'tax', width:80, align:"right",sorttype:'number',formatter:'number',summaryType:'sum'},
{name:'total',index:'total', width:80,align:"right",sorttype:'number',formatter:'number', summaryType:'sum'},
{name:'note',index:'note', width:150, sortable:false,editable:true}
],
rowNum:10,
rowList:[10,20,30],
height: 'auto',
pager: '#p48remote2',
sortname: 'invdate',
viewrecords: true,
sortorder: "desc",
caption:"Grouping with remote data",
grouping: true,
groupingView : {
groupField : ['name'],
groupColumnShow : [true],
groupText : ['<b>{0}</b>'],
groupCollapse : false,
groupOrder: ['asc'],
groupSummary : [true],
groupDataSorted : true
},
footerrow: true,
userDataOnFooter: true
});
jQuery("#48remote2").jqGrid('navGrid','#p48remote',{add:false,edit:false,del:false});
And PHP code is as below,
PHP MySQL code
examp = $_REQUEST["q"]; //Query number
$page = $_REQUEST['page']; // Get the requested page
$limit = $_REQUEST['rows']; // Get how many rows we want to have into the grid
$sidx = $_REQUEST['sidx']; // Get index row - i.e. user click to sort
$sord = $_REQUEST['sord']; // Get the direction
if(!$sidx) $sidx =1;
...
$result = mysql_query("SELECT COUNT(*) AS count FROM invheader a, clients b WHERE a.client_id=b.client_id".$wh);
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
}
else {
$total_pages = 0;
}
if ($page > $total_pages)
$page=$total_pages;
$start = $limit*$page - $limit; // Do not put $limit*($page - 1)
if ($start<0)
$start = 0;
$SQL = "SELECT a.id, a.invdate, b.name, a.amount,a.tax,a.total,a.note FROM invheader a, clients b WHERE a.client_id=b.client_id".$wh." ORDER BY ".$sidx." ".$sord. " LIMIT ".$start." , ".$limit;
$result = mysql_query( $SQL ) or die("Could not execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0; $amttot=0; $taxtot=0; $total=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$amttot += $row[amount];
$taxtot += $row[tax];
$total += $row[total];
$responce->rows[$i]['id']=$row[id];
$responce->rows[$i]['cell']=array($row[id],$row[invdate],$row[name],$row[amount],$row[tax],$row[total],$row[note]);
$i++;
}
$responce->userdata['amount'] = $amttot;
$responce->userdata['tax'] = $taxtot;
$responce->userdata['total'] = $total;
$responce->userdata['name'] = 'Totals:';
echo json_encode($responce);
But I am not able to understand the code in PHP. How can I do that?
If I understand you correct you need include summary line in the bottom of the grid. To do this you don't need the grouping part from the posted example. The only parameters which are important in your case are:
footerrow: true,
userDataOnFooter: true
If you use both from the jqGrid options you need just calculate the sum for the columns where you need it has and include "userdata" part in the JSON which produce the servlet. See here, here and here for more information.