I am working on location based service. I couldn't find any clear answer related to my following queries and so am asking-
How to enable HTML5 geolocation in our own server? Or is there any central geolocation DB there which will provide location service by default (like DNS)?
I was stunned seeing the accuracy of geolocation in google map (http://html5demos.com/geo) in my laptop (obviously GPS free) which is within ~20M range. What is the technology? How to implement that in our own system?
When I used to search my IP location, it used to show the ISP office in the map which is ~15 KM further as opposed to recent situation where it is showing almost exact location. What might be the reason? could it be because I use my android phone using the same Wireles router and it takes the location from there? Or in HTML5 they started locating specific IP addresses (which seems somewhat unlikely).
You can find a lot of information on how this works and how to use it in your own websites in the excellent Dive Into HTML 5. This book recommends using Modernizr, a simple example of which is provided:
function get_location() {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(show_map);
} else {
// no native support; maybe try Gears?
}
}
The primary way it is working on your laptop is by using the known positions of local wireless
access points. This varies a little from browser to browser - firefox has a good explanation here. They use positioning services from Google, which were created by mapping done by Google's Street View cars.
function GetGeolocation() {
navigator.geolocation.getCurrentPosition(GetCoords, GetError);
}
now check the GetCords function
function GetCoords(position){
alert('latitude: '+ position.coords.latitude);
alert('longitude: '+ position.coords.longitude);
alert('accuracy: '+ position.coords.accuracy);
FindmeOnMap(position.coords.latitude, position.coords.longitude);
}
// Check for geolocation support
if (navigator.geolocation) {
// Use method getCurrentPosition to get coordinates
navigator.geolocation.getCurrentPosition(function (position) {
// Access them accordingly
alert(position.coords.latitude + ", " + position.coords.longitude);
});
}
From
http://robertnyman.com/2010/03/15/geolocation-in-web-browsers-to-find-location-google-maps-examples/
It's actually pretty simple. The above example from Dive into HTML is incomplete, as it doesn't show the show_map function, which is a user-created function that actually reads the incoming data and does something with it. Here's a more complete example:
<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>location.html</title>
<meta charset = "UTF-8" />
<script type = "text/javascript">
//<![CDATA[
function getLoc(){
navigator.geolocation.getCurrentPosition(showMap);
} // end getLoc
function showMap(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var linkUrl = "http://maps.google.com?q=" + lat + "," + long;
var mapLink = document.getElementById("mapLink");
mapLink.href = linkUrl;
var embedMap = document.getElementById("embedMap");
embedMap.src = linkUrl + "&z=16&output=embed";
} // end showMap
//]]>
</script>
</head>
<body onload = "getLoc()">
<h1>Geolocation Demo</h1>
<p>
<a id = "mapLink"
href = "http://maps.google.com">click for a map</a>
</p>
<iframe id = "embedMap"
width="800"
height="500"
frameborder="0"
scrolling="no"
marginheight="0"
marginwidth="0"
src= "">
</iframe><br />
</body>
</html>
This example (from my upcoming HTML5 book) has a getLoc() function called by the body onload mechanism. This uses the navigator.geolocation.getCurrentPosition() function to request a permission vector. It will pop up a permission dialog, which will be rejected if the user chooses not to share her current position. If the user does play along, the indicated callback function (in my case showMap) will be displayed.
The callback function automatically accepts a special position object as its only parameter. This object has a number of potentially useful attributes, but latitude and longitude are the most helpful. You can use these values to simply print out the current position. You can also concatenate these values into a Google maps URL to get a quick Google map of the current location. I also embedded a Google map into my current page, and changed the URL of the embedded (iframe) map to get immediate feedback.
Hope this helps!
Try This Code
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API
-->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.
var map;
function initialize() {
var mapOptions = {
zoom: 6
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Related
I've noticed the message about Google deprecating reference in favour of place_id and was looking to implement it.
I am using the AutocompleteService but when I run it the response does not contain place_id, but does contain reference and id.
Here's a quick adaptation I did of the example page (I tried to put it on jsfiddle but couldn't get it to run):
<!DOCTYPE html>
<html>
<head>
<title>Retrieving Autocomplete Predictions</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
// This example retrieves autocomplete predictions programmatically
// from the autocomplete service, and displays them as an HTML list.
// The predictions will include a mix of places (as defined by the
// Google Places API) and suggested search terms.
function initialize() {
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: 'trafalgar square' }, callback);
}
function callback(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var results = document.getElementById('results');
for (var i = 0, prediction; prediction = predictions[i]; i++) {
results.innerHTML += '<li>' + prediction.description + '</li>';
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<p>Query suggestions for 'trafalgar square':</p>
<ul id="results"></ul>
</body>
</html>
Can someone explain what I'm missing / doing wrong?
Has someone got an example of the AutocompleteService with place_id being returned with the predictions/suggestions?
Thanks
Issue 6845
Bug: Google Maps JavaScript API - Autocomplete Response not included place_id
https://code.google.com/p/gmaps-api-issues/issues/detail?id=6845&q=place_id&colspec=ID%20Type%20Status%20Introduced%20Fixed%20Summary%20Stars%20ApiType%20Internal
UPDATE
This issue has been fixed
https://code.google.com/p/gmaps-api-issues/issues/detail?id=6845#makechanges
I can confirm what you're seeing. I'd guess we just need to wait for the roll out to be complete.
I am trying to create a custom Google street view of a buildings interior. I have looked many places and I have seen the basic idea of how to do it.
I have been using this link
http://googlemaps.googlermania.com/google_maps_api_v3/en/custom_streetview/index.html
as well as other examples.
They seem to have very similar code but what they all seem to lack is how to set up the files.
If someone knows where I can find a working example I should be able to work my way backwards of if someone can offer me some detailed instructions, I would be very appreciative.
I have a VirtualBox running an Ubuntu server.
On the server I have an html file named street.html(code below).
I also have a folder named "lab_tiles," which contains "lab_test," which contains several jpegs with the naming pattern XX-YY_s1.jpg(i.e. 00-00_s1.jpg, 00-01_s1.jpg, 00-02_s1.jpg)
I have the following code for the html file.
<!DOCTYPE html>
<html>
<head>
<title>Custom Street View panorama tiles</title>
<meta charset="utf-8">
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type='text/javascript'>
function code3_2() {
// Set StreetView provider.
var streetViewOptions = {
zoom: 1,
pano : "lab_test",
panoProvider: getCustomPanorama
};
// Create a StreetView object.
var streetViewDiv = document.getElementById('streetview_canvas1');
streetViewDiv.style.fontSize = "15px";
var streetView = new google.maps.StreetViewPanorama(streetViewDiv, streetViewOptions);
}
function getCustomPanoramaTileUrl(panoID, zoom, tileX, tileY) {
// Return a pano image given the panoID.
return "lab_tiles/" + panoID + '/' + tileX + '-' +tileY + '_s1.jpg';
}
function getCustomPanorama(panoID) {
var streetViewPanoramaData = {
links: [],
copyright: 'People at my job',
tiles: {
tileSize: new google.maps.Size(256, 256),
worldSize: new google.maps.Size(2048, 1024),
centerHeading: 0,
getTileUrl: getCustomPanoramaTileUrl
}
};
switch(panoID) {
case "lab_test":
streetViewPanoramaData["location"] = {
pano: 'lab_test',
description: "lab test",
latLng: new google.maps.LatLng(37.556429,-122.050745)
};
return streetViewPanoramaData;
}
}
google.maps.event.addDomListener(window, 'load', code3_2);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Looking at the link you supplied it seems you can put your (tile)images anywhere you want. The function below is used to specify the location when retrieving them.
function getCustomPanoramaTileUrl(panoID, zoom, tileX, tileY) {
// Return a pano image given the panoID.
return "ardenwood_tiles/" + panoID + '/' + tileX + '-' +tileY + '_s1.jpg';
}
In this case the images will be in the folder named ardenwood_tiles/visitor_center/
I need help with my PHP code, as I have a project where I have a private layer Fusion tables, and want to show on my website. I'm trying to use OAuth, but it shows me the coat. So the variables are captured? I have taken http://code.google.com/p/fusion-tables-api/ guide, but do not show me anything. : (
<code>
<!DOCTYPE html>
<html>
<head>
<style>
#map_canvas { width: 500px; height: 400px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?
sensor=false">
</script>
<script type="text/javascript">
var map;
var layer;
var tableid = 2102910;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(19.541451, -96.925632),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer(tableid);
layer.setQuery("SELECT 'geometry' FROM " + tableid);
layer.setMap(map);
}
</script>
</head>
<body onload="initialize();">
<div id="map_canvas"></div>
<div style="margin-top: 10px;">
</div>
<?php
include('clientlogin.php');
include('sql.php');
include('file.php');
$tableid = 2102910;
$username = "xxxxxx#gmail.com";
$password = "xxxx";
$token = ClientLogin::getAuthToken($username, $password);
$ftclient = new FTClientLogin($token);
$condition = $_POST["
echo "These Projects are in ".$condition."";
?>
</body>
</html>`
<code>
Your code is not using OAuth, but the older method "ClientLogin". If you want to use OAuth, follow the OAuth guide from Fusion Tables.
It is really simple, to get it to work:
Register your application at the API console of Google.
Then you redirect the user to the Google Authorization page
From there the user gets redirected back to your application (to the URL you specified when registering your application in the first step). In this step the authorization token is sent to your application
With this token, you can access the users fusion tables.
But just follow the guide, everything is described in detail!
I'm trying to put a Google map in my page and make it so that when the page loads the map will display exactly the location of the user. In order to do so, I've taken the google maps API code and inserted it into my HTML5 page. At first the browser did ask for permission to share my location but it isn't actually showing this location on the map; I've tried with two or more combinations of functions but it is still not working.... please, I need help! If anyone can tell me what is wrong with the code please do:
<html lang="en" manifest="halma.manifest">
<head>
<meta charset="utf-8">
<title>helmas</title>
<link rel="stylesheet" type="text/css" href="css2.css">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAycdS3aS7dItIegOaJzT2RBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSiGkO1l1KdZvNzo-8b-o7M21o4UA"></script>
<!--[if IE]>
<script src="excanvas.js"></script>
<![endif]-->
</head>
<<body onload="loadMap()" onunload="GUnload()">
<article>
<div id="map" style="width:100%;height:800px;"></div>
<script>
if (navigator.geolocation) {
// try to get the users location
}
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.watchPosition(showPositionOnMap, errorMessage,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 });
}
else {
alert("Geolocation is not supported by this browser");
}
var map = null;
function loadMap() {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(52.2021, 0.1346 ), 12); // (sets the map centre to Cambridge UK)
map.setUIToDefault();
}
function showPositionOnMap(position) {
var geoCoords = new GLatLng(position.coords.latitude, position.coords.longitude);
map.addOverlay(new GMarker(geoCoords));
}
function errorMessage(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
</script>
Perhaps the sensor parameter in the maps invocation needs to be set to "true" - at the moment you have it set to "false". So your script tag should contain this url
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAycdS3aS7dItIegOaJzT2RBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSiGkO1l1KdZvNzo-8b-o7M21o4UA"></script>
For more info:
Google Maps Api sensor location
I'm working on a website of a client, a local church. I've embedded a Google Map using the Link feature on the Maps page. The info window on the map includes "Reviews," and the church is concerned about this. Is there a way to remove that from the info window? I don't want to remove any reviews themselves, just that link on the info window?
Is this possible? Are there any other customization options (besides the size) one can manipulate via the query string?
Nearly 2 years ago, I created a custom map with complete control over the contents of the bubble, using the API and some code manipulation. Click on the above link for a demo. I've cleaned up the code for this answer, although to implement you'll need to replace all YOUR__BLANK__HERE text with the appropriate values.
Step 1: Call the gMaps API
<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_API_KEY_HERE"
type="text/javascript">
</script>
Step 2: In the body of your document, create an element with id "map". Size and position it with CSS. It requires a height and width.
<div id="map" class="content"></div>
Step 3: After the div has been defined in the DOM, it is safe to insert the following script tag:
<script type="text/javascript">
//<![CDATA[
// Check to see if this browser can run the Google API
if (GBrowserIsCompatible()) {
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var i=0;
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
// The info window version with the "to here" form open
to_htmls[i] = html +
'<br />Start address:<form action="http://maps.google.com/maps" method="get">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT">' +
'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
// "(" + name + ")" +
'"/>';
// The inactive version of the direction info
html = html + '<br><a href="javascript:tohere('+i+')">Get Directions<'+'/a>';
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers[i] = marker;
htmls[i] = html;
i++;
return marker;
}
// functions that open the directions forms
function tohere(i) {
gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
// Display the map, with some controls and set the initial location
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
YOUR_ZOOM_LEVEL_HERE // a value of 13 worked for me
);
// Set up one marker with an info window
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
/* repeat the process to add more markers
map.addOverlay(marker);
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
map.addOverlay(marker);*/
}
// display a warning if the browser was not compatible
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/
// http://www.econym.demon.co.uk/googlemaps/
//]]>
</script>
Using this code, the bubble contains the html you specify in YOUR_HTML_HERE plus a link to Get Directions, which (when clicked) turns into a textbox asking for a starting address. The result of the query, unfortunately, opens in a new browser window (since, at time of original publishing the API did not include directions capabilities)
I think I found the answer to my own question. The info window itself can't be modified, but by linking to the map for the address itself rather than the church as a business entity does the trick. The driving directions link is still there and that's mostly all they wanted.