Getting country code from Google Maps and HTML 5 GeoLocation - html

I am trying to use HTML 5 GeoLocation to get a longitude and latitude and then use Google Maps API to get the country code of that longitude/latitude. Can anybody tell me where I am going wrong in my code, I currently get the Javascript error 'this.lat is not a function' in main.js :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&v=2&key=drnhdhddfhgfghfg" type="text/javascript"></script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
$.post('http://maps.googleapis.com/maps/api/geocode/json', { latlng: latlng, sensor: false }, function (results) {
alert(results);
});
});
}
else {
alert("Geolocation services are not supported by your browser.");
}
</script>
</head>
<body>
</body>
</html>

Try this:
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[7].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
});
} else {
alert("Geolocation services are not supported by your browser.");
}
</script>
</head>
<body>
</body>
</html>

Related

How to get the current location from this here map?

Below is the code of a here map. I'd like to know how can I get the current location from the map? Anyone has ideas? Thanks in advance.
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css"
href="https://js.api.here.com/v3/3.0/mapsjs-ui.css" />
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" charset="UTF-8"
src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 700px; background: #ccc" />
<script type="text/javascript" charset="UTF-8" >
/**
* Boilerplate map initialization code starts below:
*/
function showMap(position) {
// Show a map centered at (position.coords.latitude, position.coords.longitude).
}
navigator.geolocation.getCurrentPosition(showMap);
//Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'DemoAppId01082013GAL',
app_code: 'AJKnXv84fjrb0KIHawS0Tg',
useCIT: true,
useHTTPS: true
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Eindhoven
var map = new H.Map(document.getElementById('map'), defaultLayers.normal.map, {center: {lat: 51.4484160, lng: 5.4916750}, zoom: 13}) ;
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
function addCircleToMap(map){
// Color of the dot, later on change this into interactive wheel
var dotcolor = 'green';
map.addObject(new H.map.Circle(
// The central point of the circle
{lat: 51.4484160, lng: 5.4916750},
// The radius of the circle in meters
100,
{
style: {
strokeColor: 'white', // Color of the perimeter
lineWidth: 2,
fillColor: dotcolor // Color of the circle
}
}
));
}
// Now use the map as required...
addCircleToMap(map);
</script>
</body>
</html>
Below is the code of a here map. I'd like to know how can I get the current location from the map? Anyone has ideas? Thanks in advance.
Im not sure when you are using api.here.com. Maybe you can use google.maps.Geocoder like i did below. This will set lat and lng equal to your position, if its turns on in your browser of cause.
libary:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
Js:
var geocoder;
geocoder = new google.maps.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 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]) {
alert("Found you! at Latitude: " +lat + " and Longitude: " +lng);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
latlon = new google.maps.LatLng(lat, lon)
mapholder = document.getElementById('mapholder')
mapholder.style.height = '250px';
mapholder.style.width = '500px';
var myOptions = {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
}
var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
var marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>

Google Maps API V3 - Label Fusion Tables polygons by employing InfoBox

I'm trying inside Google Maps API V3 to Label Fusion Tables polygons by employing InfoBox,
for this I use example from http://www.geocodezip.com/geoxml3_test/v3_FusionTables_zipcode_map_whiteBg.html,
but code (as shown below) do not display labels:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Label Fusion Tables polygons by employing InfoBox</title>
<style>
#map_canvas { width: 610px; height: 400px; }
.style1 {font-size: 14px}
</style>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://www.google.com/fusiontables/gvizdata?tq="></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
var map;
var labels = [];
var layer;
var tableid = 1499916;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(37.23032838760389, -118.65234375),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer(tableid);
layer.setQuery("SELECT 'geometry' FROM " + tableid);
layer.setMap(map);
codeAddress();
google.maps.event.addListener(map, "bounds_changed", function() {
displayZips();
});
google.maps.event.addListener(map, "zoom_changed", function() {
if (map.getZoom() < 11) {
for (var i=0; i<labels.length; i++) {
labels[i].setMap(null);
}
}
});
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function displayZips() {
//set the query using the current bounds
var queryStr = "SELECT geometry, ZIP, latitude, longitude FROM "+ tableid + " WHERE ST_INTERSECTS(geometry, RECTANGLE(LATLNG"+map.getBounds().getSouthWest()+",LATLNG"+map.getBounds().getNorthEast()+"))";
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(displayZipText);
}
var infowindow = new google.maps.InfoWindow();
function displayZipText(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
if (map.getZoom() < 11) return;
FTresponse = response;
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
for(i = 0; i < numRows; i++) {
var zip = response.getDataTable().getValue(i, 1);
var zipStr = zip.toString()
while (zipStr.length < 5) { zipStr = '0' + zipStr; }
var point = new google.maps.LatLng(
parseFloat(response.getDataTable().getValue(i, 2)),
parseFloat(response.getDataTable().getValue(i, 3)));
labels.push(new InfoBox({
content: zipStr
,boxStyle: {
border: "1px solid black"
,textAlign: "center"
,backgroundColor:"white"
,fontSize: "8pt"
,width: "50px"
}
,disableAutoPan: true
,pixelOffset: new google.maps.Size(-25, 0)
,position: point
,closeBoxURL: ""
,isHidden: false
,enableEventPropagation: true
}));
labels[labels.length-1].open(map);
}
}
</script>
<body onload="initialize();">
<form>
<span class="style1">Show:</span>
<input id="address" type="text" value="07646" ></input>
<input id="geocode" type="button" onclick="codeAddress();" value="Geocode"></input>
<div id="map_canvas"></div>
</body>
</html>
Does anyone have any suggestions?
Best regards,
Darko
I get a javascript error "google is undefined".
Doesn't look like you are including the Google Maps Javascript API v3 in the right place (it is needed for geoxml3 and infobox). If I fix that I see zip code labels on the polygons.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
Not sure what this is for:
<script type="text/javascript" src="http://www.google.com/fusiontables/gvizdata?tq="></script>

Google geocode is late (still one step behind)

I put there my whole code. Trying to determine location address. My script should create still one marker with geocoded address (in console - variable kktina).
But, unfortunately, there isn't everything OK. Because by script still resolves previous location (or it takes previous coordinates, dunno). Maybe there is an error in code, but I'm not able to do this anymore..
So asking for help, thank you!
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places,geometry"></script>
<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
<script>
var map,marker;
var geocoder = new google.maps.Geocoder();
var markers = [];
var img,icon,type;
var prenos,pos,address = "5",point;
function clearMarkersFromArray() {
if (markers.length>0){
markers[0].setMap(null);
markers.shift(markers[0]);
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
address = responses[0].formatted_address;
} else {
address = 'Cannot determine address at this location.';
}
});
return address;
}
function initialize() {
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(49,19),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
google.maps.event.addListener(map, 'click', function(response) {
clearMarkersFromArray();
point = new google.maps.LatLng(response.latLng.$a,response.latLng.ab);
var kktina = geocodePosition(point);
console.log(kktina);
var marker = new google.maps.Marker({
position: point,
draggable: true
});
markers.push(marker)
marker.setMap(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas" style="height:400px;width:700px;"></div>
</body>
</html>
You can't do this:
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
address = responses[0].formatted_address;
} else {
address = 'Cannot determine address at this location.';
}
});
return address;
}
the Geocoder is asynchronous, the value of address is undefined when it is returned.
Use the returned data inside the callback function instead, something like this (not tested):
var kktina = null;
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
kktina = responses[0].formatted_address;
} else {
kktina = 'Cannot determine address at this location.';
}
console.log(kktina);
var marker = new google.maps.Marker({
position: point,
draggable: true
});
markers.push(marker)
marker.setMap(map);
});
}

Google places api I want to get JSON output

I want to search for locations in a particular place on the google places api and display them on JSOn output.Suppose I want to search for all the banks my near place. How do I code for that.Can you please give sample code.
try this working code..it uses jquery mobile. it finds the places around your current lat & lon.
map.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/jquery.mobile-1.0.min.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.0.js"></script>
<script src="js/map.js"></script>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=true&libraries=places"></script>
</head>
<body>
<div data-role="page" data-theme="none" class="page-map" id="page-map">
<script src="js/canvas.js"></script>
<div id="map-canvas">
<!-- map loads here... -->
</div>
</div>
</body>
</html>
map.js
var map;
var infowindow;
var lat;
var lng;
var lng;
var service;
var reference;
var initialLocation;
$( '.page-map' ).live( 'pagecreate',function(event){
checkLocation();
});
function checkLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
lat = position.coords.latitude;
lng = position.coords.longitude;
callPlaceService(lat, lng);
}, gpsFail, {
enableHighAccuracy : true,
maximumAge : 300000
});
}
}
function callPlaceService(lat, lng) {
var pyrmont = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom : 15,
center : pyrmont,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var request = {
location : pyrmont,
radius : 5000,
//types: ['atm','bank'],
keyword : 'Bank'
};
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for ( var i = 0; i < results.length; i++) {
var requestDetails = {reference : results[i].reference};
service.getDetails(requestDetails, checkDetailedStatus);
}
}
}
function checkDetailedStatus(details, detailStatus) {
if (detailStatus == google.maps.places.PlacesServiceStatus.OK) {
var name = '{"name":"'+ details.name +'"}';
var address = '{"address":"' + details.formatted_address + '"}';
var phone = '{"phone":"' + details.formatted_phone_number+ '"}';
var website = '{"website":"' + details.website + '"}';
var full_address = name + "," + address + "," + phone + "," + website;
console.log(full_address);
var jsonTxt = JSON.stringify(full_address);
}
}
function gpsFail() {
//Geo-location is supported, but we failed to get your coordinates.
}
Try this.
Here you need to give radius according to your distance. Types may be ATM, Restaurants, Gas Station the way you needs.
You need to give places like Chennai, Bangalore, etc or you provide latitude/longitude. Describe it briefly. You in android/iphone

Google Maps API V3 and Local search problem - empty results?

I am trying to implement a Maps API V3 and Local Search but I seem to be having problems. Somehow, the results in the OnLocalSearch() function is empty.
Here is my complete code:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
// do stuff when DOM is ready
var geocoder = new google.maps.Geocoder();
var address = '{{string_location}}';
var map;
// Our global state for LocalSearch
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gLocalSearch = new GlocalSearch();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[0].geometry.location.lat())
//alert(results[0].geometry.location.lng())
//Create the Map and center to geocode results latlong
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
gLocalSearch.setSearchCompleteCallback(this, OnLocalSearch);
gLocalSearch.execute("{{business_item.name}}");
}
else {
alert('No results found. Check console.log()');
console.log("Geocoding address: " + address);
console.log("Geocoding failed: " + status);
}
});
}
/*
Other functions
*/
function OnLocalSearch() {
if (gLocalSearch.results[0]) { //This is empty. Why?
var resultLat = gLocalSearch.results[0].lat;
var resultLng = gLocalSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("not found!");
}
}
});
//]]>
</script>
FYI, I am using this as an example and I am stuck for a few hours now about this: http://gmaps-samples-v3.googlecode.com/svn-history/r136/trunk/localsearch/places.html
Any reply will be greatly appreciated.
Regards,
Wenbert
UPDATE
I made a mistake somewhere here:
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0" type="text/javascript"><;/script>
<script src="http://maps.google.com/maps/api/js?v=3.1&sensor=false&region=PH"></script>
Also, make sure you double check the address you are geocoding. I am from the Philippines and it seems that Google only geocodes Major Roads. See http://gmaps-samples.googlecode.com/svn/trunk/mapcoverage_filtered.html
Thanks to jgeerdes from irc.geekshed.net #googleapis
Just making a couple of tweaks so that the code is actually complete, and using an address I know will be geocoded successfully plus a query I know will return something, your code works. Here is what I did:
<html>
<head>
<title>Wenbert test</title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
//<![CDATA[
google.load('jquery','1.4.2');
google.load('maps','3',{other_params:'sensor=false'});
google.load('search','1');
alert('starting...');
$(document).ready(function() {
alert('here');
// do stuff when DOM is ready
var geocoder = new google.maps.Geocoder();
var address = '4019 lower beaver rd. 50310';
var map;
// Our global state for LocalSearch
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gLocalSearch = new GlocalSearch();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[0].geometry.location.lat())
//alert(results[0].geometry.location.lng())
//Create the Map and center to geocode results latlong
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
gLocalSearch.setSearchCompleteCallback(this, OnLocalSearch);
gLocalSearch.execute("debra heights wesleyan church");
}
else {
alert('No results found. Check console.log()');
console.log("Geocoding address: " + address);
console.log("Geocoding failed: " + status);
}
});
}
/*
Other functions
*/
function OnLocalSearch() {
if (gLocalSearch.results[0]) { //This is empty. Why?
var resultLat = gLocalSearch.results[0].lat;
var resultLng = gLocalSearch.results[0].lng;
var point = new google.maps.LatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("not found!");
}
}
});
//]]>
</script>
</head>
<body>
<div id="map_canvas" style="height:100%;"></div>
</body>
</html>