Parse a google maps xml with xPath + Javascript - javascript

I am a bit confused on how to go about developing an application, using Google maps javascript API + the 'Places' library.
What I want to have:
an html page with 2 divs:
a. left div: contains the google map + results/markers based on a given location ( I have that already)
b. right div: contains a list of the results with drop-down menus to filter the results on the map, on the left div.
So my questions are:
a. The response is already loaded in an object for the map on the left div, as in this example:
https://developers.google.com/maps/documentation/javascript/examples/place-search
Do I need to load it again - in order to get this information in XML and parse it in the right div?
My xml request is for example:
https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=34.680617,33.043263&radius=500&types=store&key=AIzaSyDQ9fpqxWt0F5EsztFt-HSjcSQruJSGeik
Where would I insert this (in the above example code) in order to get the xml response and parse the file/node information in text format on the right div?
b. In the callback function there is a loop that goes through the results:
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
Could I use that same loop in order to parse the xml nodes without having to load the xml file again?
If yes, the google developers site does not have an example of how to do that. It only lists a few xPath expressions:
developers.google.com/maps/documentation/webservices/index#ParsingXML
but it does not provide a full complete example from scratch.
i.e. how to use xPath to parse the xml file with javascript
c. if we need to have 2 separate responses (the google maps api + the web service), how will these 2 communicate between them then?
Not sure if I got it all wrong here...
thanks,
k.

Yes you should be able to use the same loop to parse the xml you could try something like:
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
// Untested but use JQuery and try this:
var name = $(results[i]).find('name').text();
var location = $(results[i]).find('location');
var lat = $(location).find('lat').text();
var lng = $(location).find('long').text();
var obj =
{
name: name,
lat : lat,
lng: lng
};
createMarker(obj);
}
}
}
I would keep track of the markers your creating in an array or something to manage them on the map.

Related

Create multiple marker points on Google Maps In a Web Application from C# objects

I've got a Web Application with C# code that creates a list of objects with their long and lat. I want to then create marker points on Google Maps for them using Javascript. I've currently got this code:
var marker;
for (var i = 0; i < ('<%= Buses.Count %>' - 1); i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng('<%= Buses['i'].latitude %>', '<%= Buses['i'].longitude %>'),
map: map
});
}
Which does not work, I believe the error is with where I reference "i" to say which object in the list to use.
If I manually set a marker point without a for loop and change ['i'] to [0] it will place a marker fine. However, due to the number of items changing and reaching up to 100 I require using a for loop. I have tried removing the '' around i and this generates an error saying
"i does not exist in the current context."
I have seen these posts:
Add two marker points in google maps
Google Maps JS API v3 - Simple Multiple Marker Example
Google Maps JS API v3 - Simple Multiple Marker Example
However, all of these are using locations inside of the JavaScript. My objects are contained within the C# code as a custom object defined as:
public static List<Bus> Buses = new List<Bus>();
This is my C# Code in full:
https://pastebin.com/2M1hWjnM
You're mixing a javascript for with data in code-behind/C#. It not works.
First, you've to put the marks data on a javascript array. Then make your for without webforms tags <%%>
put something like this on your page code behind (C#)
public static string getBusesJson()
{
var buses = new List<Bus>();
buses.Add(new Bus() {latitude = 10, longitude = 20 });
buses.Add(new Bus() { latitude = 15, longitude = 30 });
buses.Add(new Bus() { latitude = 5, longitude = 40 });
return JsonConvert.SerializeObject(buses);
}
put this on your aspx header:
<script type="text/javascript">
var points = <%= WebApplication3.WebForm1.getBusesJson()%>;
for (var i = 0; i < points.length; i++) {
//pass points[i].latitude and points[i].longitude to google maps
}
</script>

How to get JSON from googlemaps url

As you can see here, I need those markers values such as lat lng address.
From that link, i tried to go to those link. But still can not inspect anything.
i tried this in Js but it did not return anything
var url = "https://www.google.com/maps/d/u/0/viewer?ll=41.042268%2C29.001695&spn=0.06531%2C0.072004&hl=en&t=m&vpsrc=6&msa=0&source=embed&ie=UTF8&mid=zsrW6PXLEpZk.kTAwhQ8bgERs" + "&sensor=false";
$.getJSON(url, function (data) {
for(var i=0;i<data.results.length;i++) {
var adress = data.results[i].formatted_address;
alert(adress);
}
});
http://jsfiddle.net/CursedChico/NNuDe/341/
How can i get? I am used to Js, angularjs, java and android.
You can't get markers data from that url you provided, it uses kml format to get values. Anyways, you want to get location, address etc. Basically you want informations of all markers. Here is the solution:
1) Get KML file of the map.
What is KML data?
KML is a file format used to display geographic data in an Earth
browser such as Google Earth
In your link, you can download it by clicking left menu->download kml->export to kml and you have the kml file. Than parse the kml data into json using a parser like this.
2) Check if the company let you use JSONP
If the page you are looking for have JSONP set, you can easily retrieve data by injecting JSONP link into your HTML as a script and get than using the callback function. Here is a working project which gets lat and long datas by calling JSONP.
function setJSONP(code) {
var script = document.createElement('script');
script.src = "http://www.nike.com/store-locator/locations?jsoncallback=callback" +
"&country_code=US" +
"&format=JSON" +
"&type=country" +
"&_=1461335132869";
document.getElementsByTagName('head')[0].appendChild(script);
}
?jsoncallback=yourFunctionName
then use your function, in this example callback() is our function.
function callback(data) {
//use data here which is returned JSON from server
var lat = data.lat;
...
}

Get the parameters of a JavaScript function with Scrapy

I was wondering if it is possible to extract the parameters of a JavaScript function with Scrapy, from a code similar to this one:
<script type="text/javascript">
var map;
function initialize() {
var fenway = new google.maps.LatLng(43.2640611,2.9388228);
};
}
</script>
I would like to extract the coordinates 43.2640611 and 2.9388228.
This is where re() method would help.
The idea is to locate the script tag via xpath() and use re() to extract the lat and lng from the script tag's contents. Demo from the scrapy shell:
$ scrapy shell index.html
>>> response.xpath('//script').re(r'new google\.maps\.LatLng\(([0-9.]+),([0-9.]+)\);')
[u'43.2640611', u'2.9388228']
where index.html contains:
<script type="text/javascript">
var map;
function initialize() {
var fenway = new google.maps.LatLng(43.2640611,2.9388228);
};
}
</script>
Of course, in your case the xpath would not be just //script.
FYI, new google\.maps\.LatLng\(([0-9.]+),([0-9.]+)\); regular expression uses the saving groups ([0-9.]+) to extract the coordinate values.
Also see Using selectors with regular expressions.
Disclaimer: I haven't tried this approach, but here's how I would think about it if I was constrained to using Scrapy and didn't want to parse JavaScript the way alecxe suggested above. This is a finicky, fragile hack :-)
You can try using scrapyjs to execute the JavaScript code from your scrapy crawler. In order to capture those parameters, you'd need to do the following:
Load the original page and save it to disk.
Modify the page to replace google.maps.LatLng function with your own (see below). make sure to run your script AFTER google js is loaded.
Load the modified page using scrapyjs (or the instance of webkit created by it)
Parse the page, look for the two special divs created by your fake LatLng function that contain the extracted lat and lng variables.
More on step 2: Make your fake LatLng function modify the HTML page to expose lat and lng variables so that you could parse them out with Scrapy. Here is some crude code to illustrate:
var LatLng = function LatLng(lat, lng) {
var latDiv = document.createElement("div");
latDiv.id = "extractedLat";
latDiv.innerHtml = lat;
document.body.appendChild(latDiv);
var lngDiv = document.createElement("div");
lngDiv.id = "extractedLng";
lngDiv.innerHtml = lng;
document.body.appendChild(lngDiv);
}
google = {
map: {
LatLng: LatLng
}
};
Overall, this approach sounds a bit painful, but could be fun to try.

Dynamically change color of polygon in linked KML file

I am looking to create a Choropleth map made up of polygons overlaid atop Google Earth via the plug-in using JavaScript.
The polygons exist in a KML file, all with unique IDs, on a server (not necessarily mine).
I want to be able to change the color of the polygon dynamically to show different data sets.
Is this doable?
I looked up the KML mechanism, but that only works with files on the same server.
Thanks,
Bill
You can load/parse remote KML via the Google Earth API from any network accessible URL (same server or otherwise) then iterate over the KML objects and programmatically change the styles and the polygon colors.
var href = 'http://code.google.com/'
+ 'apis/earth/documentation/samples/kml_example.kml';
google.earth.fetchKml(ge, href, function(kmlObject) {
if (kmlObject) {
checkObject(kmlObject);
// append KML objects to current view
ge.getFeatures().appendChild(kmlObject);
}
});
function checkObject(kmlObject) {
var type = kmlObject.getType();
if (type == 'KmlDocument' || type == 'KmlFolder') {
var features = kmlObject.getFeatures();
if (features.hasChildNodes()) {
var children = features.getChildNodes();
for (i=0; i < children.getLength(); i++) {
checkObject(children.item(i));
}
}
} else if (type == 'KmlPlacemark') {
// check/set style, change color, etc.
// ...
}
}
Reference:
https://developers.google.com/earth/documentation/kml#fetchkml_and_parsekml

geoxml3 and placemarks not functioning

Well I've read through and tried to find out the solutions but fail...
I followed the instructions from the geoxmlv3: http://code.google.com/p/geoxml3/wiki/Usage
here is a quote from that document:
<script type="text/javascript">
var myParser = new geoXML3.parser({afterParse: useTheData});
myParser.parse('my_geodata.kml');
function useTheData(doc) {
// Geodata handling goes here, using JSON properties of the doc object
for (var i = 0; i < doc.placemarks.length; i++) {
doSomething;
}
};
</script>
According to the documentation, the doc.placemarks should be working and return an array of json of placemarks in the KML file, unfortunately this 'doc' doesn't even exist(undefined), any idea?
If you are using the poly branch, "doc" is an array.
function useTheData(doc) {
// Geodata handling goes here, using JSON properties of the doc object
for (var i = 0; i < doc[0].placemarks.length; i++) {
doSomething;
}
};
I will fix the example in the documentation.
working example
Why don't you use KmlLayer of Google Maps API v3?
It's easy to map information from KML file onto the map.
https://developers.google.com/maps/documentation/javascript/layers#KMLLayers

Categories

Resources