How to parse array of json objects to custom XML (node.js) - json

I'm trying to use js2xmlparser (node.js) to transform an array of JSON objects into a custom XML file.
The source array looks like this:
[
{
"ID": "3233705000002165882",
"Quarter": "2020Q3",
"Pkg_Total": "0.00",
"Course_Each": "0.00"
},
{
"ID": "3233705000002165883",
"Quarter": "2020Q4",
"Pkg_Total": "2.50",
"Course_Each": "0.70"
},
{
"ID": "3233705000002165884",
"Quarter": "2021Q1",
"Pkg_Total": "34.00",
"Course_Each": "15.00"
}
]
I need the target XML to look like this:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<records>
<record id="3233705000002165882">
<column name="Quarter">
<value><![CDATA[2020Q3]]></value>
</column>
<column name="Pkg_Total">
<value><![CDATA[$ 0.00]]></value>
</column>
<column name="Course_Each">
<value><![CDATA[$ 0.00]]></value>
</column>
</<record>
<record id="3233705000002165883">
<column name="Quarter">
<value><![CDATA[2020Q4]]></value>
</column>
<column name="Pkg_Total">
<value><![CDATA[$ 2.50]]></value>
</column>
<column name="Course_Each">
<value><![CDATA[$ 0.70]]></value>
</column>
</<record>
<record id="3233705000002165884">
<column name="Quarter">
<value><![CDATA[2021Q1]]></value>
</column>
<column name="Pkg_Total">
<value><![CDATA[$ 34.00]]></value>
</column>
<column name="Course_Each">
<value><![CDATA[$ 15.00]]></value>
</column>
</<record>
</<records>
</response>
Any suggestions on how to configure js2xmlparser to do this? Or is there another node.js utility that can help with this transformation task? Thank you!

I solved this by writing my own custom function:
const json2XML = async (jsonFilePathName) => {
const jsonObj = await loadDataObj(jsonFilePathName)
let xmlRecords = '';
let xmlRecordBegin = '';
let xmlRecordFull;
jsonObj.forEach((newRecord) => {
const fieldNames = Object.keys(newRecord);
let colElements = '';
let colElement;
let colValue;
xmlRecordBegin = `<record id="${newRecord.ID}">`;
fieldNames.forEach((fieldName) => {
//iterate through all fieldNames except ID
if (fieldName !== 'ID') {
colValue = newRecord[fieldName];
colElement = `<column name="${fieldName}"><value><![CDATA[${colValue}]]></value></column>`;
colElements = colElements + colElement;
}
});
//end fieldNames.forEach((fieldName)
xmlRecordFull = xmlRecordBegin + colElements + '</record>';
//console.log('xmlRecordFull = ', xmlRecordFull);
xmlRecords = xmlRecords + xmlRecordFull;
});
//end jsonObj.forEach((newRecord)
xmlDoc = xmlDecl + xmlRootBegin + xmlRecordsBegin + xmlRecords + xmlRecordsEnd + xmlRootEnd;
return xmlDoc;
}

Related

Soap xml to json for vue-quasar

i have a soap response with this format
<soap:Envelope xmlns:soap="somelink">
<soap:Body>
<ns1:queryDataResponse xmlns:ns1="somelink">
<WindowTabData NumRows="3" TotalRows="3" StartRow="0" xmlns="somelink">
<DataSet>
<DataRow>
<field column="Value">
<val>JoeBlock</val>
</field>
<field column="Name">
<val>Joe Block</val>
</field>
</DataRow>
<DataRow>
<field column="Value">
<val>GardenUser</val>
</field>
<field column="Name">
<val>GardenUser BP</val>
</field>
</DataRow>
<DataRow>
<field column="Value">
<val>SeedFarm</val>
</field>
<field column="Name">
<val>Seed Farm Inc.</val>
</field>
</DataRow>
</DataSet>
<RowCount>3</RowCount>
<Success>true</Success>
</WindowTabData>
</ns1:queryDataResponse>
</soap:Body>
</soap:Envelope>
and i need to parse it into json with something like
[
{"value": "JoeBlock", "Name":"Joe Block"},
{"Value": "GardenUser", "Name": "GardenUser BP"},
{"Value": "SeedFarm", "Name": "Seed Farm Inc."},
...
]
anyone can give me an example to parse it?
i tried using domparser like
let parser = new DOMParser()
let doc = parser.parseFromString(xmls, 'application/xml')
doc.querySelectorAll('DataRow').forEach(cap => {
console.log('parser', cap.textContent)
})
but all i got was
["JoeBlockJoe Block", "GardenUserGardenUser BP", "SeedFarmSeed Farm Inc."]
please help how to extract field column as key and separate the value
this is what i ended up doing
xmlparser(xmls) {
let convert = require('xml-js')
let parser = new DOMParser()
let doc = parser.parseFromString(xmls, 'application/xml')
let x = doc.getElementsByTagName('DataSet')
let out = convert.xml2json(x[0].outerHTML, {
compact: true,
spaces: 4
})
let outp = JSON.parse(out)
this.CreateJson(outp.DataSet.DataRow)
},
CreateJson(data) {
let json = []
for (let i = 0; i < data.length; i++) {
let array = {}
for (let j = 0; j < data[i].field.length; j++) {
array[data[i].field[j]._attributes.column] =
data[i].field[j].val._text
}
json[i] = array
}
console.log('json created : ', JSON.stringify(json, null, 4))
}
not that elegant solution yeah, so im open to suggestion to make it more elegant

Have index value as nodes while converting XML to Json using Json.Net

I have an input XML as below:
<Options>
<Series>
<Series>
<Type>Bar</Type>
<TargetAxisIndex>1</TargetAxisIndex>
</Series>
<Series>
<Type>Line</Type>
<TargetAxisIndex>2</TargetAxisIndex>
</Series>
</Series>
<Title>Test title</Title>
</Options>
I am using JsonConvert.SerializeXmlNode() and want to have my output as below:
{"Series":
{
"0": {"Type":"Bar","TargetAxisIndex":"1"},
"1": {"Type":"Line","TargetAxisIndex":"2"}
}
"Title":"Test title"
}
Is there a way of achieving this? Basically i want the node to be serialized as index.
If you don't mind going through an intermediate projection through an anonymous class, and switching from XmlDocument to the more Linq-friendly XDocument, you'll be able to leverage the Select overload which provides the index, and then apply .ToDictionary to get the Json shape you need:
var root = XDocument.Load(pathToMyDocument)
.Root;
var myObject = new
{
Title = root.Element("Title").Value,
Series = root.Element("Series")
.Elements("Series")
.Select((node, idx) =>
new
{
Node = node,
Index = idx
})
.ToDictionary(
e => e.Index,
e => new
{
Type = e.Node.Element("Type").Value,
TargetAxisIndex = e.Node.Element("TargetAxisIndex").Value
})
};
var json = JsonConvert.SerializeObject(myObject);
Result:
{
"Title": "Test title",
"Series": {
"0": {
"Type": "Bar",
"TargetAxisIndex": "1"
},
"1": {
"Type": "Line",
"TargetAxisIndex": "2"
}
}
}
Another alternative may be to do the dictionary and indexing manipulation in XSLT, before using SerializeXmlNode, by using the position() function, although you'll need to subtract 1 - it's one based.

Kendo Diagram Datasource - json

Goal: Use kendo ui diagram component to draw a department to project workflow
The workflow is structured in the following manner:
Each Department may have multiple Strategies, each Strategy may have multiple Programs and each Program may have multiple projects.
I have a WCF service that when called returns a json string.
The service calls a stored proc that returns XML, in vb.net then I convert that XML into json (using json.net).
service code:
Public Function GetStakeholderRelationshipMatrix(StakeholderId As Integer) As String
Try
conn.Open()
Dim da = New SqlDataAdapter()
sCommand = New SqlCommand("uspGetRelationshipMatrix", conn)
sCommand.CommandType = CommandType.StoredProcedure
sCommand.Parameters.AddWithValue("#StakeholderId", StakeholderId)
xmlDoc.LoadXml(sCommand.ExecuteScalar())
Return JsonConvert.SerializeXmlNode(xmlDoc)
Catch ex As Exception
Return -1
End Try
End Function
XML Data
<Departments>
<Department Id="7" Name="Information Technology Department">
<Strategies Id="21" Name="Increase Revenue">
<Programs Id="45" Name="Program1">
<Projects Id="4" Name="test3" />
</Programs>
<Programs Id="49" Name="Program4">
<Projects Id="2" Name="Test1" />
<Projects Id="3" Name="Test2" />
</Programs>
</Strategies>
</Department>
</Departments>
Json Converted Data:
{"d":"{\"Departments\":{\"Department\":{\"#Id\":\"7\",\"#Name\":\"Information Technology Department\",\"Strategies\":{\"#Id\":\"21\",\"#Name\":\"Increase Revenue\",\"Programs\":[{\"#Id\":\"45\",\"#Name\":\"Program1\",\"Projects\":{\"#Id\":\"4\",\"#Name\":\"test3\"}},{\"#Id\":\"49\",\"#Name\":\"Program4\",\"Projects\":[{\"#Id\":\"2\",\"#Name\":\"Test1\"},{\"#Id\":\"3\",\"#Name\":\"Test2\"}]}]}}}}"}
I am have been unable to bind the data (json) to the diagram component in order to successfully display the workflow. I need help binding the json string to the diagram component.
Kendo code:
<div id="visual"></div>
var dsRelationshipMatrix = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: "wcf service return json string",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (result) {
var obj = $.parseJSON(result.d);
if (obj == null) {
options.success([]);
} else {
options.success(obj);
}
},
error: function (result) {
options.error(result)
}
});
}
},
schema: {
data: function (data) {
return data
}
}
}); //closes data source
function createDiagram() {
$("#visual").kendoDiagram({
dataSource: new kendo.data.HierarchicalDataSource({
data: dsRelationshipMatrix,
schema: {
model: {
children: "Strategies"
}
}
}),
layout: {
type: "layered"
},
shapeDefaults: {
visual: visualTemplate
},
connectionDefaults: {
stroke: {
color: "#979797",
width: 2
}
}
});
var diagram = $("#visual").getKendoDiagram();
diagram.bringIntoView(diagram.shapes);
}
After going through the pain for some time, I got it to work and wanted to share that information with everyone. This might not be the perfect way but it is one of the ways to do it.
The key is going to be the structure of the SQL data (extracted as XML).
In SQL I ended up performing a recursive loop that extracts the data and formats it into XML. So a root node of ROOT encompasses an item (Department - there can only be one department) and each hierarchical category has an items section with an item section as a child of items. Wording the structure is rather difficult so...
SQL:
SELECT
--dStakeholder.StakeholderId AS '#Id',
dStakeholder.FunctionalDepartment as 'item/info' ,
'#1696d3' as 'item/colorScheme',
(SELECT
--dStrategy.StrategyId AS '#Id',
dStrategy.StrategyDescription 'item/info',
'#1696d3' as 'item/colorScheme' ,
(Select
--dPrograms.ProgramId as '#Id',
dPrograms.ProgramDescription 'item/info' ,
'#1696d3' as 'item/colorScheme' ,
(Select
--dHeaders.ProjectId as '#Id',
dHeaders.ProjectName 'item/info',
'#1696d3' as 'item/colorScheme'
from
dbo.ProjectHeaders as dHeaders
inner join (select distinct projectid, programid, departmentid from dbo.ProjectHeaders) as pp
on dHeaders.ProjectId = pp.ProjectId
where pp.ProgramId = dPrograms.ProgramId and pp.departmentid = dStakeholder.Stakeholderid
FOR XML PATH(''), TYPE
) as 'item/items'
from
dbo.ProjectPrograms as dPrograms
inner join (select distinct programid, strategyid , departmentid from dbo.ProjectHeaders) as sp
on dPrograms.ProgramId = sp.ProgramId
where sp.StrategyId = dStrategy.StrategyId and sp.departmentid = dstakeholder.stakeholderid
FOR XML PATH(''), TYPE
) as 'item/items'
FROM
dbo.ProjectStrategies as dStrategy
inner join (select distinct strategyid , departmentid from dbo.ProjectHeaders) as bss
on dStrategy.StrategyId = bss.StrategyId
WHERE
dStakeholder.StakeholderId = bss.DepartmentId
FOR XML PATH(''), TYPE
) as 'item/items'
FROM
dbo.Stakeholders as dStakeholder
FOR XML PATH('root'), type
My data from the sql appears in XML in this manner:
<root>
<item>
<info>ERISA Compliance Services Department</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>New Commission</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Program3</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>test3</info>
<colorScheme>#1696d3</colorScheme>
</item>
</items>
</item>
</items>
</item>
<item>
<info>SAGA Development</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Program1</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Test1</info>
<colorScheme>#1696d3</colorScheme>
</item>
</items>
</item>
<item>
<info>Program4</info>
<colorScheme>#1696d3</colorScheme>
<items>
<item>
<info>Test2</info>
<colorScheme>#1696d3</colorScheme>
</item>
</items>
</item>
</items>
</item>
</items>
</item>
</root>
Now I go through my xml and grab the important information. Code in VB.net. There is a class for item that just list the properties that I would need.
conn.Open()
Dim dt As New DataTable
Dim da As New SqlDataAdapter("uspGetRelationshipMatrix " + Convert.ToString(StakeholderId), conn)
da.Fill(dt)
Dim sb = New StringBuilder()
If dt.Rows.Count <> 0 Then
For Each row As DataRow In dt.Rows
sb.Append(row.Item("Data"))
Next
End If
conn.Close()
xmlDoc.LoadXml(sb.ToString)
Dim itemList As New List(Of Item)
Dim RootNode As XmlNode
RootNode = xmlDoc.SelectSingleNode("/root")
For Each DeptNode As XmlNode In RootNode.ChildNodes
Dim deptItem As New Item
'check to ensure that is not nothing
Dim info As XmlNode = DeptNode.SelectSingleNode("info")
Dim cs As XmlNode = DeptNode.SelectSingleNode("colorScheme")
deptItem.info = info.InnerText
deptItem.colorScheme = cs.InnerText
'Begin items loop for child nodes
Dim stratItems As XmlNode = DeptNode.SelectSingleNode("items")
For Each stratItemNode As XmlNode In stratItems.ChildNodes
Dim stratItem As New Item
Dim stratinfo As XmlNode = stratItemNode.SelectSingleNode("info")
Dim stratcs As XmlNode = stratItemNode.SelectSingleNode("colorScheme")
stratItem.info = stratinfo.InnerText
stratItem.colorScheme = stratcs.InnerText
'place start loop
Dim progItems As XmlNode = stratItemNode.SelectSingleNode("items")
For Each progItemNode As XmlNode In progItems.ChildNodes
Dim progItem As New Item
Dim proginfo As XmlNode = progItemNode.SelectSingleNode("info")
Dim progcs As XmlNode = progItemNode.SelectSingleNode("colorScheme")
progItem.info = proginfo.InnerText
progItem.colorScheme = progcs.InnerText
'place start loop
Dim projItems As XmlNode = progItemNode.SelectSingleNode("items")
For Each projItemNode As XmlNode In projItems.ChildNodes
Dim projItem As New Item
Dim projinfo As XmlNode = projItemNode.SelectSingleNode("info")
Dim projcs As XmlNode = projItemNode.SelectSingleNode("colorScheme")
projItem.info = projinfo.InnerText
projItem.colorScheme = projcs.InnerText
'place start loop
'place end loop
progItem.items.Add(projItem)
Next
'place end loop
stratItem.items.Add(progItem)
Next
'place end loop
deptItem.items.Add(stratItem)
Next
'end items loop
itemList.Add(deptItem)
Next
I then use newtonsoft json in vb.net in order to present the information as a json string.
Json string:
[ 
{ 
"info":"ERISA Compliance Services Department",
"colorScheme":"#1696d3",
"items":[ 
{ 
"info":"New Commission",
"colorScheme":"#1696d3",
"items":[ 
{ 
"info":"Program3",
"colorScheme":"#1696d3",
"items":[ 
{ 
"info":"test3",
"colorScheme":"#1696d3",
"items":[ 
]
}
]
}
]
},
{ 
"info":"SAGA Development",
"colorScheme":"#1696d3",
"items":[ 
{ 
"info":"Program1",
"colorScheme":"#1696d3",
"items":[ 
{ 
"info":"Test1",
"colorScheme":"#1696d3",
"items":[ 
]
}
]
},
{ 
"info":"Program4",
"colorScheme":"#1696d3",
"items":[ 
{ 
"info":"Test2",
"colorScheme":"#1696d3",
"items":[ 
]
}
]
}
]
}
]
}
]
With the json formatted in this structure, now I just plugged my json to kendo diagram and now you get a visual hierarchical image of flow.

sapui5 data from json

Have problem to read data from json. My login.json file
{
"Users": [
{
"login" : "admin",
"password" : "admin"
}
]
}
Here is my login.xml.view
<core:View
controllerName="sap.ui.demo.myFiori.view.login"
xmlns="sap.m"
xmlns:l="sap.ui.layout"
xmlns:core="sap.ui.core" >
<Page
title="{i18n>LoginIn}">
<VBox
class="marginBoxContent" >
<items>
<Label text="User" />
<Input
id="nameInput"
type="Text"
placeholder="..." />
<Label text="password" />
<Input
id="passwInput"
type="Password"
placeholder=" ..." />
<Text id="description" class="marginOnlyTop" />
<Button text="Login" press="handleContinue" />
</items>
</VBox>
</Page>
</core:View>
and login.controller.js
jQuery.sap.require("sap.ui.demo.myFiori.util.Formatter");
sap.ui.controller("sap.ui.demo.myFiori.view.login", {
handleContinue : function (evt) {
var name = this.getView().byId("nameInput").getValue();
var paswd = this.getView().byId("passwInput").getValue();
if (name == "log" && paswd == "pass") {
var context = evt.getSource().getBindingContext();
this.nav.to("Master", context);
}
else {
jQuery.sap.require("sap.m.MessageToast");
sap.m.MessageToast.show("Wrong login");
}
}
});
This login screen works, but I can't get login and password from json file and currently these data are taken from if sentence, which is not good. Any suggestions?
First, I am assuming that this is just a test app, as having the correct plain text auth credentials actually in the client app is rather bad practice ...
The crux of your question seems to be: "How can I access JSON data from a file?"
There is a Q&A already on SO with that theme: How to get data from a json file? but if you want to use a model, which is a common practice in UI5 apps, then you could:
1) Create a JSON model, specifying the name of the JSON file; the JSONModel mechanism will take care of the loading; assign this to the view
this.getView().setModel(new sap.ui.model.json.JSONModel('login.json'), "login");
2) Access the data in the JSON model when you need to check, using the getData() method
// Note - extremely bad practice - don't do this for real!
var authinfo = this.getView().getModel("login").getData().Users[0];
if (name == authinfo.login && paswd == authinfo.password) {
....
(I'm indexing 0 of Users as you seem to have your authinfo inside an array)
Maybe I defined something wrong before but now it works. I changed login.controller.js. Now it looks like this:
jQuery.sap.require("sap.ui.demo.myFiori.util.Formatter");
sap.ui.controller("sap.ui.demo.myFiori.view.login", {
onInit: function () {
var oModels = new sap.ui.model.json.JSONModel("login.json");
sap.ui.getCore().setModel(oModels);
},
handleContinue : function (evt) {
var authinfo = this.getView().getModel().getData().Users[0];
var name = this.getView().byId("nameInput").getValue();
var paswd = this.getView().byId("passwInput").getValue();
if (name == authinfo.login && paswd == authinfo.passw) {
var context = evt.getSource().getBindingContext();
this.nav.to("Master", context);
}
else {
jQuery.sap.require("sap.m.MessageToast");
sap.m.MessageToast.show("Wrong login");
}
}
});

Using Google Maps API to get Address of Business

I have a requirement and I am hoping Google Maps API will have a solution. I have never used Google Maps API - so I am very new to this.
On the website homepage there is a form, when a user comes, I want the following things to happen:
1) The city field should be populated with users city based on IP
2) There is a second field called store name - when the user starts typing the store name - I want to fetch all business listings with that name in that city and show it as a drop down from which the user can select the appropriate branch. There is no need for anything to be shown on the map.
Egs - If a user in houston starts typing McDonalds, the following business listings should start showing up
McDonalds, 12 Pearland Ave, Houston TX
McDonalds, 2600 Bary Area Blvd, Houston TX
McDonalds, 262 Clearlake Blvd, Houston TX
Also when we get the address for a business listing from Google API - do we get it as one String and we need to parse it or do we get it different fields Street Name, City, State, Zip code etc
Any information or examples will be really appreciated
Thanks
I don't think you want Google Maps. First of all the terms of use do not allow any use other than displaying things on a Google Map on a publicly accessible webpage, second, there is another Google API that does exactly what you need: the Client location API: http://code.google.com/apis/ajax/documentation/#ClientLocation
Concerning the "businesses": You're going to have to source that data from somewhere - I do not believe google has a service for that. Perhaps you could simply use the Google Search API and some logic to find only businesses (http://code.google.com/apis/ajaxsearch/)
EDIT: I for the businesses, perhaps you could take a look at this sample: http://code.google.com/apis/ajaxsearch/samples.html#local-search
updated: here is an example of using the google clientlocation api and localsearch using jsonp.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAALDWeTDQHOJCbCf0JnUqL8BT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQA7AE8xB9MyWgHECPY2qimOp7BUQ"></script>
<script src="scripts/clientLocation.js" type="text/javascript"></script>
<script src="scripts/localSearch.js" type="text/javascript"></script>
<script type="text/javascript">
function $g(id) {
return document.getElementById(id);
}
function displayLocation(latitudeEl, longitudeEl, cityEl, regionEl, countryEl, country_codeEl) {
var cloc = new ClientLocation.Location(google.loader.ClientLocation);
if (latitudeEl) latitudeEl.innerHTML = cloc.latitude;
if (longitudeEl) longitudeEl.innerHTML = cloc.longitude;
if (cityEl) cityEl.innerHTML = cloc.address.city;
if (regionEl) regionEl.innerHTML = cloc.address.region;
if (country) country.innerHTML = cloc.address.country;
if (country_codeEl) country_codeEl.innerHTML = cloc.address.country_code;
}
function localSearch(term, callback, context) {
var cloc = new ClientLocation.Location(google.loader.ClientLocation);
var searchUrl = 'http://www.google.com/uds/GlocalSearch?callback=' + callback + '&context=' + context + '&hl=en&q=' + encodeURIComponent(term) + '&sll=' + cloc.latitude + ',' + cloc.longitude + '&key=ABQIAAAALDWeTDQHOJCbCf0JnUqL8BT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQA7AE8xB9MyWgHECPY2qimOp7BUQ&v=1.0';
// http://jaybyjayfresh.com/2007/09/17/using-script-tags-to-do-remote-http-calls-in-javascript/
scriptLoaded = function() {
removeNode(newScript);
};
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.onload = scriptLoaded;
newScript.src = searchUrl;
headID.appendChild(newScript);
}
function search() {
var term = $g("txtSearch").value;
localSearch(term, "displayResults", "0");
}
function displayResults(context, results, status, details, unused) {
var titles = [];
for (var i = 0; i < results.results.length; i++) {
// this cast is not necessary, just here to illustrate
// vs intellisense and reduce coding errors.
var result = new LocalSearch.Result(results.results[i]);
titles.push(result.title);
}
$g("searchResults").innerHTML = titles.join("</br>");
}
function init() {
displayLocation($g("latitude"), $g("longitude"), $g("city"), $g("region"), $g("country"), $g("country_code"));
}
</script>
</head>
<body onload="init()">
<form id="form1" runat="server">
<div>
latitude : <span id="latitude"></span>
<br />
longitude : <span id="longitude"></span>
<br />
city : <span id="city"></span>
<br />
region : <span id="region"></span>
<br />
country : <span id="country"></span>
<br />
country_code : <span id="country_code"></span>
<br />
</div>
<input type="text" id="txtSearch" /><input type="button" id="btnSearch" value="get results"
onclick="search();" /><br />
<div id="searchResults">
</div>
</form>
</body>
</html>
// <copyright file="clientLocation.js" company="Sky Sanders">
// This source is placed in the Public Domain.
// http://skysanders.net/subtext
// Attribution is appreciated.
// </copyright>
/*
object literal format for google.loader.clientlocation
{
"latitude": 33.324,
"longitude": -111.867,
"address": {
"city": "Chandler",
"region": "AZ",
"country": "USA",
"country_code": "US"
}
}
*/
var ClientLocation = {};
ClientLocation.Address = function() {
/// <field name="city" type="String" />
/// <field name="region" type="String" />
/// <field name="country" type="String" />
/// <field name="country_code" type="String" />
/// <returns type="ClientLocation.Address"/>
if (arguments.length > 0) {
this.city = arguments[0].city;
this.region = arguments[0].region;
this.country = arguments[0].country;
this.country_code = arguments[0].country_code;
return;
}
else {
this.city = "";
this.region = "";
this.country = "";
this.country_code = "";
}
}
ClientLocation.Location = function() {
/// <field name="latitude" type="Number" />
/// <field name="longitude" type="Number" />
/// <field name="address" type="ClientLocation.Address" />
if (arguments.length > 0) {
this.latitude = arguments[0].latitude;
this.longitude = arguments[0].longitude;
this.address = arguments[0].address;
}
else {
this.latitude = 0;
this.longitude = 0;
this.address = undefined;
}
}
// <copyright file="localSearc.js" company="Sky Sanders">
// This source is placed in the Public Domain.
// http://skysanders.net/subtext
// Attribution is appreciated.
// </copyright>
/*
GlocalSearch result
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "computed",
"listingType": "local",
"lat": "33.389689",
"lng": "-111.853909",
"accuracy": "8",
"title": "Best \u003cb\u003eBuy\u003c/b\u003e",
"titleNoFormatting": "Best Buy",
"ddUrl": "http://www.google.com/maps....",
"ddUrlToHere": "http://www.google.com/maps?....",
"ddUrlFromHere": "http://www.google.com/maps?....",
"streetAddress": "1337 South Alma School Road",
"city": "Mesa",
"region": "AZ",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?....",
"url": "http://www.google.com/maps/place?source....",
"content": "",
"maxAge": 604800,
"phoneNumbers": [{
"type": "",
"number": "(480) 644-7139"
},
{
"type": "",
"number": "(480) 464-0444"
}],
"addressLines": ["1337 South Alma School Road", "Mesa, AZ"]
}
*/
var LocalSearch = {};
LocalSearch.PhoneNumber = function() {
/// <field name="type" type="String"/>
/// <field name="number" type="String"/>
/// <returns type="LocalSearch.PhoneNumber"/>
if (arguments.length > 0) {
this.type = arguments[0].type;
this.number = arguments[0].number;
}
else {
this.type = "";
this.number = "";
}
}
LocalSearch.Result = function() {
/// <field name="GsearchResultClass" type="String"/>
/// <field name="viewportmode" type="String"/>
/// <field name="listingType" type="String"/>
/// <field name="lat" type="String"/>
/// <field name="lng" type="String"/>
/// <field name="accuracy" type="String"/>
/// <field name="title" type="String"/>
/// <field name="titleNoFormatting" type="String"/>
/// <field name="ddUrl" type="String"/>
/// <field name="ddUrlToHere" type="String"/>
/// <field name="ddUrlFromHere" type="String"/>
/// <field name="streetAddress" type="String"/>
/// <field name="city" type="String"/>
/// <field name="region" type="String"/>
/// <field name="country" type="String"/>
/// <field name="staticMapUrl" type="String"/>
/// <field name="url" type="String"/>
/// <field name="content" type="String"/>
/// <field name="maxAge" type="Number"/>
/// <field name="phoneNumbers" type="Array"/>
/// <field name="addressLines" type="Array"/>
// <returns type="LocalSearch.Result"/>
if (arguments.length > 0) {
this.GsearchResultClass = arguments[0].GsearchResultClass;
this.viewportmode = arguments[0].viewportmode;
this.listingType = arguments[0].listingType;
this.lat = arguments[0].lat;
this.lng = arguments[0].lng;
this.accuracy = arguments[0].accuracy;
this.title = arguments[0].title;
this.titleNoFormatting = arguments[0].titleNoFormatting;
this.ddUrl = arguments[0].ddUrl;
this.ddUrlToHere = arguments[0].ddUrlToHere;
this.ddUrlFromHere = arguments[0].ddUrlFromHere;
this.streetAddress = arguments[0].streetAddress;
this.city = arguments[0].city;
this.region = arguments[0].region;
this.country = arguments[0].country;
this.staticMapUrl = arguments[0].staticMapUrl;
this.url = arguments[0].url;
this.content = arguments[0].content;
this.maxAge = arguments[0].maxAge;
this.phoneNumbers = arguments[0].phoneNumbers;
this.addressLines = arguments[0].addressLines;
}
else {
this.GsearchResultClass = "";
this.viewportmode = "";
this.listingType = "";
this.lat = "";
this.lng = "";
this.accuracy = "";
this.title = "";
this.titleNoFormatting = "";
this.ddUrl = "";
this.ddUrlToHere = "";
this.ddUrlFromHere = "";
this.streetAddress = "";
this.city = "";
this.region = "";
this.country = "";
this.staticMapUrl = "";
this.url = "";
this.content = "";
this.maxAge = 0;
this.phoneNumbers = [];
this.addressLines = [];
}
}
If you're only looking up restaurants, try using Yelp's API. You can search for a business by its name within a search radius. Their API is also simpler and easier to use than google's.
http://www.yelp.com/developers/documentation/search_api