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.
Related
I'm struggling to get a Google Places lookup AND Geocoding to work together in the same page. I think there's a conflict in how I'm loading the two APIs.
I'm using this one to load the places API
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=*****************&callback=initAutocomplete&types=address" async defer></script>
Places lookup works fine with that.
For Geocoding, this is the first line of code I'm trying to get working
geocoder = new google.maps.Geocoder();
And it works (well, doesn't throw an error) if I include this in my page:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
But that's pretty much the same URL I already have, and including it breaks the Places lookup. When I have both scripts included I also get a warning telling me I've included the Maps API multiple times which may cause problems.
Please could someone show me which script(s) to include for both to work together? I'm finding the docs pretty confusing at this point to be honest.
It should work fine with just your first include. It contains the base Google Maps API plus the Places library.
var initMap = function () {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: '10 Downing St, Westminster, London SW1A 2AA, UK',
}, function (results, status) {
if (status === 'OK') {
var result = results[0];
alert('latitude: ' + result.geometry.location.lat());
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
};
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAiv004_zrkpEL-v1u-LU6QYIkgv7yjT_M&language={{ Lang::getLocale() }}&libraries=places&" />
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
var options = {
types: ['(cities)']
};
var places = new google.maps.places.Autocomplete(document.getElementById('location'));
var inputLat = $("input[name*='lat']");
var inputLng = $("input[name*='lng']");
var inputPlaceId = $("input[name*='place_id']");
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var address = place.formatted_address;
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
var placeId = place.place_id;
inputLat.val(latitude);
inputLng.val(longitude);
inputPlaceId.val(placeId);
});
});
$('#location').keypress(function(e) {
if (e.which == 13) {
google.maps.event.trigger(autocomplete, 'place_changed');
return false;
}
});
</script>
I need it to display only cities, but somehow I get countries too.. I don't want to display continents and countries. please help
If you check the autocomplete documentation, it is stated here that:
the (cities) type collection instructs the Places service to return
results that match either locality or administrative_area3
So like you have done, you need the cities as types parameter.
What you can do is to specify the country in the Google API call with a help of region parameter. Just check this tutorial on how to do that.
Here is the sample request:
= javascript_include_tag "http://maps.google.com/maps/api/js?v=3.13&sensor=false&libraries=places®ion=UK"
For more information, check this related SO question it may give you an idea on how to solve this issue.
Google maps Autocomplete: output only address without country and city
Is there a way to get only the city name from Google Places API instead of getting the whole location?
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/
Hitting a page with the follow script displays:
lat: undefined
lon: 51.5001524
Why is it that while lat is undefined, lon is not?
A working example can be found here.
Pull up your web console and see for yourself!
$(document).ready(function(){
var geocoder;
function codeAddress()
{
geocoder = new google.maps.Geocoder();
var address = 'London, England';
geocoder.geocode({'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
lat = results[0].geometry.location.Ia;
lon = results[0].geometry.location.Ja;
console.log("lat: " + lat);
console.log("lon: " + lon);
}
});
}
codeAddress();
});
</script>
</head>
<body>
</body>
</html>
While we're at it - what is the historical significance of Ia and Ja? I presume it relates to the Cartesian unit vectors i and j (predominately used in Engineering) though I'm not sure.
I found other examples online who use .lat for .Ia and .lng for .Ja
These, however, are returning in the console:
function () {
return this[a];
}
Just need a kick in the right direction.
Thank you.
I would use lat() and lng():
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
This is a designed behaviour of the geocoder: google shifts the identifiers in
geometry.location.Ia;
geometry.location.Ja;
on a weekly basis, i.e. from above to
geometry.location.Ja;
geometry.location.Ka;
and so on, so it is not possible to refer by id to the geocoder result object.
Chances are Google are using a javascript minifier (e.g. http://jscompress.com/) which renames all variables - hence they're subject to change on every build.
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>