Google ClientLocation API issue - javascript

I am using google API to detect client location however it always shows to me "Your Location Was Not Detected By Google Loader".
I need to find country code of the client location however it is not working for me.
<script src="http://www.google.com/jsapi" language="javascript"></script>
<script language="javascript">
if (google.loader.ClientLocation != null) {
document.write("Your Location Is: " + google.loader.ClientLocation.address.country_code);
} else {
document.write("Your Location Was Not Detected By Google Loader");
}
</script>

ClientLocation object returns null when Google cannot geolocate your IP address. This could happen because of many reasons, one being the API cannot resolve your IP address.
Maybe you can try other solutions such as
http://html5demos.com/geo
or ask your server to do this.

Try this:
<script type="text/javascript">
if(google.loader.ClientLocation) {
var latitude = google.loader.ClientLocation.latitude;
var longtitude = google.loader.ClientLocation.longitude;
var city = google.loader.ClientLocation.address.city;
var region = google.loader.ClientLocation.address.region;
var country = google.loader.ClientLocation.address.country;
var countrycode = google.loader.ClientLocation.address.country_code;
} else {
// ClientLocation not found or not populated
// so perform error handling
}
</script>
Change
if (google.loader.ClientLocation != null) {
to
if (google.loader.ClientLocation){
Hope, this helps.

Related

Get geolocation on submit in Google Forms using Google Script

I have a Google Form where I want to get the user geolocation along with the inputs.
Currently, I'm able to get it by making the user click on a url after he submits the answers. This is the code in Google Script that does it:
function doGet() {
return HtmlService.createHtmlOutputFromFile("Index");
}
function getLoc(value) {
var destId = FormApp.getActiveForm().getDestinationId() ;
var ss = SpreadsheetApp.openById(destId) ;
var respSheet = ss.getSheets()[0] ;
var data = respSheet.getDataRange().getValues() ;
var headers = data[0] ;
var numColumns = headers.length ;
var numResponses = data.length;
var c=value[0]; var d=value[1];
var e=c + "," + d ;
if (respSheet.getRange(1, numColumns).getValue()=="GeoAddress") {
respSheet.getRange(numResponses,numColumns-2).setValue(Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy HH:mm:ss"));
respSheet.getRange(numResponses,numColumns-1).setValue(e);
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns).setValue(f);
}
else if (respSheet.getRange(1,numColumns).getValue()!="GeoAddress") {
respSheet.getRange(1,numColumns+1).setValue("GeoStamp");
respSheet.getRange(1,numColumns+2).setValue("GeoCode");
respSheet.getRange(1,numColumns+3).setValue("GeoAddress");
}
}
And the Index.html file:
<!DOCTYPE html>
<html>
<script>
(function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
})()
function showPosition(position){
var a= position.coords.latitude;
var b= position.coords.longitude;
var c=[a,b]
getPos(c)
function getPos(value){
google.script.run.getLoc(value);
}
}
</script>
</html>
Instead of making the user click on a url, I want the geolocation to be automatically inputed into the response sheet as the user submits the form. I'm able to make the getLoc function run on a submit trigger, however the html function doesn't run. I believe it might be because the doGet function is already a trigger, but it requires a browser page to be opened in order to run. If that's the case, the ideal solution would be to redirect the browser to the Google Script url after the user submits it, but I can't seem to find a way to do it. Is this the correct approach and how can I make it work?
Thanks in advance!
Maybe this works: https://www.youtube.com/watch?v=J93uww0vMFY
Tutorial on Geotagging (Geo-stamp and Time-stamp) google forms.
Add info on Latitude, Longitude, and Address (Street name and number, city, state, zip code, and country) of a device submitting google forms. Linking user’s location within google forms.
Google forms integration with google maps.
Links to download the scripts are given below:
Code.gs : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1D4vTzUGZAf3_ZDVMeW760i1KoZCn37un&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4
Index.html : https://www.youtube.com/redirect?v=J93uww0vMFY&event=video_description&q=https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1mYZGYNrXNOxUD8DlDmRdBajy1nc3FKtw&redir_token=VQ2rLeQvyQea-mq9_kGhh_Kxihd8MTU5MTgxOTM2OEAxNTkxNzMyOTY4

How to display location of visitor? [duplicate]

This question already has answers here:
Getting the location from an IP address [closed]
(20 answers)
Closed 2 years ago.
I managed to get the user's latitude and longitude using HTML-based geolocation.
//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get latitude and longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
}
I want to display the city name, it seems the only way to get it is to use a reverse geolocation API. I read Google's documentation for reverse geolocation but I don't know how to get the output on my site.
I don't know how to go use this: "http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true" to display the city name on the page.
How can I achieve this?
You would do something like that using Google API.
Please note you must include the google maps library for this to work. Google geocoder returns a lot of address components so you must make an educated guess as to which one will have the city.
"administrative_area_level_1" is usually what you are looking for but sometimes locality is the city you are after.
Anyhow - more details on google response types can be found here and here.
Below is the code that should do the trick:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
$.ajax({
url: "https://geolocation-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<div>Latitude: <span id="latitude"></span></div>
<div>Longitude: <span id="longitude"></span></div>
<div>IP: <span id="ip"></span></div>
Using html5 geolocation requires user permission. In case you don't want this, go for an external locator like https://geolocation-db.com IPv6 is supported. No restrictions and unlimited requests allowed.
JSON: https://geolocation-db.com/json
JSONP: https://geolocation-db.com/jsonp
Example
For a pure javascript example, without using jQuery, check out this answer.
Another approach to this is to use my service, http://ipinfo.io, which returns the city, region and country name based on the user's current IP address. Here's a simple example:
$.get("http://ipinfo.io", function(response) {
console.log(response.city, response.country);
}, "jsonp");
Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
You can get the name of the city, country, street name and other geodata using the Google Maps Geocoding API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
console.log(position.coords.latitude)
console.log(position.coords.longitude)
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function(location) {
console.log(location)
})
}
function error(err) {
console.log(err)
}
</script>
</body>
</html>
and to display this data on the page using jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<p>Country: <span id="country"></span></p>
<p>State: <span id="state"></span></p>
<p>City: <span id="city"></span></p>
<p>Address: <span id="address"></span></p>
<p>Latitude: <span id="latitude"></span></p>
<p>Longitude: <span id="longitude"></span></p>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function(location) {
$('#country').html(location.results[0].address_components[5].long_name);
$('#state').html(location.results[0].address_components[4].long_name);
$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
})
}
function error(err) {
console.log(err)
}
</script>
</body>
</html>
Here is updated working version for me which will get City/Town, It looks like some fields are modified in the json response. Referring previous answers for this questions. ( Thanks to Michal & one more reference : Link
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
// Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng);
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
console.log("City: " + address_component.address_components[0].long_name);
itemLocality = address_component.address_components[0].long_name;
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
geolocator.js can do that. (I'm the author).
Getting City Name (Limited Address)
geolocator.locateByIP(options, function (err, location) {
console.log(location.address.city);
});
Getting Full Address Information
Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.
var options = {
enableHighAccuracy: true,
fallbackToIP: true, // fallback to IP if Geolocation fails or rejected
addressLookup: true
};
geolocator.locate(options, function (err, location) {
console.log(location.address.city);
});
This uses Google APIs internally (for address lookup). So before this call, you should configure geolocator with your Google API key.
geolocator.config({
language: "en",
google: {
version: "3",
key: "YOUR-GOOGLE-API-KEY"
}
});
Geolocator supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and a lot more features...
After some searching and piecing together a couple of different solutions along with my own stuff, I came up with this function:
function parse_place(place)
{
var location = [];
for (var ac = 0; ac < place.address_components.length; ac++)
{
var component = place.address_components[ac];
switch(component.types[0])
{
case 'locality':
location['city'] = component.long_name;
break;
case 'administrative_area_level_1':
location['state'] = component.long_name;
break;
case 'country':
location['country'] = component.long_name;
break;
}
};
return location;
}
You can use https://ip-api.io/ to get city Name. It supports IPv6.
As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.
Javascript Code:
$(document).ready(function () {
$('#btnGetIpDetail').click(function () {
if ($('#txtIP').val() == '') {
alert('IP address is reqired');
return false;
}
$.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
function (result) {
alert('City Name: ' + result.city)
console.log(result);
});
});
});
HTML Code
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
<input type="text" id="txtIP" />
<button id="btnGetIpDetail">Get Location of IP</button>
</div>
JSON Output
{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}
}
As #PirateApp mentioned in his comment, it's explicitly against Google's Maps API Licensing to use the Maps API as you intend.
You have a number of alternatives, including downloading a Geoip database and querying it locally or using a third party API service, such as my service ipdata.co.
ipdata gives you the geolocation, organisation, currency, timezone, calling code, flag and Tor Exit Node status data from any IPv4 or IPv6 address.
And is scalable with 10 global endpoints each able to handle >10,000 requests per second!
This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.
$.get("https://api.ipdata.co?api-key=test", function(response) {
$("#ip").html("IP: " + response.ip);
$("#city").html(response.city + ", " + response.region);
$("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>ipdata.co - IP geolocation API</h1>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>
The fiddle; https://jsfiddle.net/ipdata/6wtf0q4g/922/
Here is another go at it .. Adding more to the accepted answer possibly more comprehensive .. of course switch -case will make it look for elegant.
function parseGeoLocationResults(result) {
const parsedResult = {}
const {address_components} = result;
for (var i = 0; i < address_components.length; i++) {
for (var b = 0; b < address_components[i].types.length; b++) {
if (address_components[i].types[b] == "street_number") {
//this is the object you are looking for
parsedResult.street_number = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "route") {
//this is the object you are looking for
parsedResult.street_name = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_1") {
//this is the object you are looking for
parsedResult.sublocality_level_1 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_2") {
//this is the object you are looking for
parsedResult.sublocality_level_2 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_3") {
//this is the object you are looking for
parsedResult.sublocality_level_3 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "neighborhood") {
//this is the object you are looking for
parsedResult.neighborhood = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "locality") {
//this is the object you are looking for
parsedResult.city = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
parsedResult.state = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "postal_code") {
//this is the object you are looking for
parsedResult.zip = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "country") {
//this is the object you are looking for
parsedResult.country = address_components[i].long_name;
break;
}
}
}
return parsedResult;
}
Here's an easy function you can use to get it. I used axios to make the API request, but you can use anything else.
async function getCountry(lat, long) {
const { data: { results } } = await axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${GOOGLE_API_KEY}`);
const { address_components } = results[0];
for (let i = 0; i < address_components.length; i++) {
const { types, long_name } = address_components[i];
if (types.indexOf("country") !== -1) return long_name;
}
}
Alternatively you could use my service, https://astroip.co, it is a new Geolocation API:
$.get("https://api.astroip.co/?api_key=1725e47c-1486-4369-aaff-463cc9764026", function(response) {
console.log(response.geo.city, response.geo.country);
});
AstroIP provides geolocation data together with security datapoints like proxy, TOR nodes and crawlers detection. The API also returns currency, timezones, ASN and company data.
It is a pretty new api with an average response time of 40ms from multiple regions around the world, which positions it in the handful list of super fast Geolocation APIs available.
Big free plan of up to 30,000 requests per month for free is available.

Input location with Yahoo's weather API using simpleWeather.js?

I'm building a web-page that shows the weather. I would like for it to be able to use geolocation, as well as the option to manually input a location to pull weather information. I've got the geolocation working fine, but am unsure as to how to add an additional input using either a city or zipcode.
Here's my relevant code:
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
loadWeather(position.coords.latitude + ',' + position.coords.longitude);
});
} else {
loadWeather("", "1062617");
}
function loadWeather(location, woeid) {
$.simpleWeather({
location: location,
woeid: woeid,
unit: 'f',
success: function(weather) {
$(".weather-text").html(weatherText[weather.code]);
$(".weather-icon").html('<i class="icon-' + weather.code + '"></i>');
$(".weather-stats").html('<ul><li><strong>'+weather.city+', ' +weather.region+ '</strong></li>');
$(".weather-stats").append('<li>'+ weather.temp + '°F / '+ weather.alt.temp +'°C</li></ul>');
},
error: function(error) {
$("#weather").html('<p>' + error + '</p>');
}
});
}
I'm pretty new to javascript & jquery, so I understand how to make an input box with HTML but am unsure how to use the user input data to then retrieve the associated weather data.
The getCurrentPosition gives you access to the position interface which then gives you the coordinates. So your if statement results in a latitude and longitude based on the device's Geolocation. In order to get this same information from a user's input (latitude and longitude), you need to convert the input (could be City, State or a full address) to coordinates. I recommend using Google maps API to convert that user input.
Once converted, you can then pass the lat and long to loadWeather(). Here's an example of a user's input (Address) converted:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var address = jQuery('#address').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
jQuery('#coordinates').val(latitude+', '+longitude);
loadWeather(latitude + ',' + longitude);
}
});
</script>
<input id="address" type="text" placeholder="Enter City, State"/>
Of course you would use the above within proper context such as checking whether geolocation worked first or whenever a user actually enters their address. You might need a Google Maps API for this bit that should be easy to get.
Give it a shot, if stuck, check out this fiddle: jsfiddle
EDIT:
I grabbed Yahoo's Weather API endpoint and here is working fiddle:
https://jsfiddle.net/mjsgwq55/3/
I highly recommend logging variables so you can tell what time of data they contain. In your fiddle, you tried to access a property that doesn't exist in the object. Logging that would easily show you what to use.

How do use the varible outside of the function?

I have created a function to get the IP Address of the user. Then I tried to give separate AD to the user. So I use if condition and try to use the value of the function (getIP) to execute the if condition. But I am not success. The main problem is that I couldn't able to use the ip variable out side of the function. Can anybody see to help me.
<script type="application/javascript">
function getIP(json) {
ip=json.ip; //Here I got the user IP Address
}
getIP(json);
var KivaHan="221.120.101.58"
var Office="221.120.99.186"
if( ip==KivaHan ){
document.write("Kiva Han IP Address: " + ip);
}else{
document.write("Office IP Address: " + ip);
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Change it like this.
function getIP(json) {
return json.ip;
}
var ip = getIP(json);
If your getIP function is synchronous, return the IP address from it:
function getIP() {
var ip; // Don't forget to declare this
// ...get the IP address into `ip`
return ip;
}
usage
var ip = getIP();
if (ip) {
// Your code uses `ip` here
} else {
// Failed to get it, handle that here
}
If your getIP function is asynchronous, you have two options:
Have it accept a callback, and call the callback with the IP:
function getIP(callback) {
var ip; // Don't forget to declare this
// ...get the IP address into `ip`, maybe have it set to null on error
callback(ip);
}
usage:
getIP(function(ip) {
if (ip) {
// Your code uses `ip` here
} else {
// Failed to get it, handle that here
}
});
Or use a Promise (ES2015, but there are libs that polyfill it well enough on JavaScript engines that don't do it natively):
function getIP(callback) {
var ip; // Don't forget to declare this
return new Promise(function(resolve, reject) {
// ...get the IP address into `ip`
if (/* we got the IP */) {
resolve(ip);
} else {
// it failed:
reject();
}
});
}
usage:
getIP()
.then(function(ip) {
// Your code uses `ip` here; perhaps ip == null means failure
})
.catch(function() {
// Failed to get it, handle that here
});
Only place where javascript creates a new scope is function. Whenever you see function keyword, its safe to assume that a new scope will be created. The problem you are facing here is you are defining ip inside a function and trying to access it outside which is logically not possible. However, you can make a global variable and can access it anywhere in your program. But downside of it is, it will clutter your global namespace and if you are unlucky you may face issues that will be weird and hard to debug.
You can make use of IIFE (Immediately Invoked function expression) which is one of the most used design pattern in javascript.
(function(){
var ip = ""; //Define ip variable here.
function getIP(json) {
ip=json.ip; //Here I got the user IP Address
}
getIP(json);
var KivaHan="221.120.101.58"
var Office="221.120.99.186"
if( ip==KivaHan ){
document.write("Kiva Han IP Address: " + ip);
}
else{
document.write("Office IP Address: " + ip);
}
})();
Hope this be of some help.
Happy Learning :)
I have tried with most of the Solution but not get real output which I want. Perhaps there is problem withe the function getIP(json) and the site from where I get the function to get user IP address. I think the value of this can't run out side of the function. So I used another site to get the user IP.
Now I give the alternative solution of my demand.
In this topic I want the IP Address of an user which I get in that function. But I could not trace out this from the function which I couldn't use more time in this page.
So I use the solution given below to fill my demand..
<head>
<script type="text/javascript" src="https://l2.io/ip.js?var=userip"> </script><!-- To get IP Address of the user -->
<script type="text/javascript"><!-- Here variables are decleared.. -->
var userip;
var KivaHan="221.120.101.58"
var Office="221.120.99.186"
</script>
</head>
<!-- Javascript for tracking and comparing the user IP-->
<!-- Below code is for implementation-->
<div class="main-bottom">
<div class="ad">
<script type="text/javascript">
if (userip==KivaHan){
document.write("Welcome");
}
else
{
document.write("Coming Soon");
}
</script>
</div>
<div class="ad">
<script type="text/javascript">
if (userip==KivaHan){
document.write("Welcome");
}
else
{
document.write("Coming Soon");
}
</script>
</div>
<div class="ad">
<script type="text/javascript">
if (userip==KivaHan){
document.write("Welcome");
}
else
{
document.write("Coming Soon");
}
</script>
</div>
</div>

Google Map javascript MarkerManager markers not showing

I have a map that reads an XML file; it's all very simple and copied from here:
http://geochalkboard.wordpress.com/2009/03/30/reading-xml-files-with-the-google-maps-api/
My version is here:
http://www.cloudfund.me/maps/mashup.html and the data file it's reading is here:
converted.xml in the same directory.
I don't get any points at all, when I run it. I put some console logging in to see if I could see anything, but as far as that's concerned, it just runs through without a hitch. The file loads ok, and I can watch the code loop through all the rows (208 in this example) without any problems.
The only warning I'm getting is the 'Resource interpreted as other passed as undefined' one; having had a look at some of the other threads, I can't see anything that helps - no empty src links, etc. As far as I can tell, this shouldn't stop it marking the points, either.
Here's the real kicker - in trying to trace this error, I set up an exact replica of the original code on my own server, and got an error about null fields, which I added some conditional code to to sort; this version works on my server. This is austin.html in the same directory (sorry, can't do more than two links in my first posts!)
So - my code is this:
<title>Test </title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=AIzaSyDgybFoyn3i5j_6d7ul7p2dPNQ5b1xOWnk"
type="text/javascript">console.log("Loaded Maps API");</script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js">console.log("MarkerManager");</script>
<script type="text/javascript">
console.log("Into Main Script");
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(51.39906378, -2.449545605), 13);
map.setUIToDefault();
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addMapType(G_PHYSICAL_MAP);
map.setMapType(G_PHYSICAL_MAP);
console.log("Reached end of map initialising");
addMarkersFromXML();
console.log("MarkersfromXML")
}
}
function addMarkersFromXML(){
var batch = [];
mgr = new MarkerManager(map);
var request = GXmlHttp.create();
console.log("About to open converted.xml")
request.open('GET', 'converted.xml', true);
console.log("Opened Converted.xml")
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200)
{
var xmlDoc = request.responseXML;
var xmlrows = xmlDoc.documentElement.getElementsByTagName("row");
for (var i = 0; i < xmlrows.length; i++) {
var xmlrow = xmlrows[i];
console.log("Running through row number",i)
var xmlcellLongitude = xmlrow.getElementsByTagName("longitude")[0];
console.log(xmlcellLongitude);
var xmlcellLatitude = xmlrow.getElementsByTagName("latitude")[0];
var point = new GLatLng(parseFloat(xmlcellLatitude.firstChild.data),parseFloat(xmlcellLongitude.firstChild.data));
//get the PAO
var xmlcellAssetName = xmlrow.getElementsByTagName("pao")[0];
console.log(xmlcellAssetName);
var celltextAssetName = xmlcellAssetName.firstChild.data;
//get the area
var xmlcellArea = xmlrow.getElementsByTagName("area")[0];
console.log(xmlcellArea);
var celltextArea = xmlcellArea.firstChild.data;
//get the land type
var xmlcellLandType = xmlrow.getElementsByTagName("landtype")[0];
console.log(xmlcellLandType);
var celltextLandType = xmlcellLandType.firstChild.data;
//get the Planning Permissions
var xmlcellPlanning = xmlrow.getElementsByTagName("planning")[0];
console.log(xmlcellPlanning);
var celltextPlanning = xmlcellPlanning.firstChild.data;
var htmlString = "Asset Name: " + celltextAssetName + "<br>" + "Size: " + celltextArea + "<br>" + "Land Type: " + celltextLandType + "<br>" + "Planning Permissions: " + celltextPlanning;
//var htmlString = 'yes'
var marker = createMarker(point,htmlString);
batch.push(marker);
}
mgr.addMarkers(batch,50);
mgr.refresh();
}
}
request.send(null);
}
function createMarker(point,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 1100px; height: 700px"></div>
</body>
</html>
Think you have a typo. In your code, you're pulling an incomplete URL for the API:
<script src="//maps.google.com/maps?file=api&v=2&sensor=false&key=AIzaSyDgybFoyn3i5j_6d7ul7p2dPNQ5b1xOWnk"
That errant // seems to be throwing the code off.
Though, to be perfectly honest, the originating example (and austin.html) doesn't exactly work as one would imagine it should. The points do get rendered, but no effective clustering takes place when you zoom out. Suspect that the 2.0 branch of the API got moved to a newer version and created a bit of an incompatibility.
Recommend that you rewrite this in API version 3. There is a cluster manager that works for it quite well.
See http://tools.voanews2.com/nuclear_reactors/

Categories

Resources