Google places api I want to get JSON output - google-maps

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

Related

Using geo location to set google maps centre

I am aiming to have a map that centre's on a user's current location with markers pulled from a mysql database displayed. I can make my map display a certain lat or lng when specified but I am having trouble taking the user's current location and using this to modify the map's centre.
Any help would be appreciated!
:)
<!DOCTYPE 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>PHP/MySQL & Google Maps Example</title>
<script src="markerclusterer.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js? key="
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
}
else{
alert("Sorry, browser does not support geolocation!");
}
}
var customIcons = {
restaurant: {
icon: 'http://orthodontistsearch.com.au/data/documents/Icon.png',
},
bar: {
icon: 'http://orthodontistsearch.com.au/data/documents/Icon.png',
}
};
function load() {
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng('latitude' , 'longitude'),
zoom: 4,
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var type = markers[i].getAttribute("type");
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var html = name + "<br>" + "Address: " + address + "<br>" + "Phone Number: " + phone + "<br>" + " Website: " + url + "<br>" ;
infowindow.setContent(html);
infowindow.open(map, marker, html);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<style type="text/css">
div#map { margin: 0 auto 0 auto; }
</style>
<div id="map" style="width: 80%; height: 500px"></div>
</body>
i m uploading demo code which i have used in my system for map display in center. Hope this will help you.
Logic
$result_count = $query_count->result(); //Count row
$count = $result_count[0]->total / 2;
if($count % 2 == 0){
$cal = $count - 0.5;
$query_latlng = $this->db->query("SELECT latitude, longitude FROM 'table_name' WHERE id = '$cal' ");
$result_latlng = $query_latlng->result();
}
else{
$cal = $count;
$query_latlng = $this->db->query("SELECT latitude, longitude FROM 'table_name' WHERE id = '$cal' ");
$result_latlng = $query_latlng->result();
}
Google Map
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $result_latlng[0]->latitude; ?>,<?php echo $result_latlng[0]->longitude; ?>),
zoom: 4,
mapTypeId: 'roadmap'
});

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>

How can I specify Google map with driving direction in jQuery mobile

I have done a Google Maps based application in PhoneGap (jQuery mobile). The task is to connect the starting and finishing locations. I am able to link these points by using marker and polyline technique. I can get only a straight line which is connecting both. But, I want to link the two locations via the driving path between these two locations. Like the marked area from the map below. Please help me on this.
I have my code here: http://jsfiddle.net/rajmathan/NALA5/
Update: I also find a code in ActionScript with the same functionality.But,I do not know how to use this in mycode
var directionOptions:DirectionsOptions = new DirectionsOptions({language: 'en',countryCode: 'US,DE',travelMode: DirectionsOptions.TRAVEL_MODE_DRIVING});
<script>
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
});
function onSuccess(position) {
var vLatitude = 18.9750;
var vLongitude = 72.8258;
var cur_lat = position.coords.latitude;
var cur_lng = position.coords.longitude;
var start = cur_lat+","+cur_lng;
var end = vLatitude+","+vLongitude;
var url = 'https://maps.google.com/?saddr='+start+'&daddr='+end;
location.href = url;
}
function onError(error)
{
alert((error.code)
}
</script>
If you are working with PhoneGap , you should install InAppBrowser and open url like this.. instead of location.href
var ref = window.open(url, 'random_string', 'location=no');
OR
You can also do with...
HTML
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div style="width:100%; margin:0px 0px 0 0px; float:left;">
<div id="map_canvas" style="width:100%;height:250px; position:relative; bottom:5px;top:5px;"></div>
</div>
<div class="restaurant_block_content" id="tGetDirection"></div>
JAVASCRIPT
var cur_lat = "";
var cur_lng = ""
var vLatitude = "";
var vLongitude = "";
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var start = '23.0300, 72.5800';
var end = '18.9750, 72.8258';
//var start = cur_lat+","+cur_lng;
// var end = vLatitude+","+vLongitude;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myRoute = response.routes[0];
/* instructions */
var txtDir = '<div><strong>Total Distance : '+myRoute.legs[0].distance.text+'</strong></div><div><strong>Total Duration : '+myRoute.legs[0].duration.text+'</strong></div><ol>';
for (var i=0; i<myRoute.legs[0].steps.length; i++) {
if(myRoute.legs[0].steps[i].maneuver.length > 0)
maneuver = '<img src="img/'+myRoute.legs[0].steps[i].maneuver+'.png" style="margin-right:10px;width:12px; height:12px;" >'
else
maneuver = "";
txtDir += '<li>'+maneuver+myRoute.legs[0].steps[i].instructions+' <br><strong style="float:right;">'+myRoute.legs[0].steps[i].distance.text+'</strong></li>';
//alert(myRoute.legs[0].steps[i].maneuver.length)
//google.maps.geometry.encoding.decodePath(myRoute.legs[0].steps[i].polyline.points)straight
}
txtDir += '</ol>';
document.getElementById('tGetDirection').innerHTML = txtDir;
$('#tGetDirection').show();
$.mobile.hidePageLoadingMsg();
}
});
}

How to generate url link to google map from nearbySearch() results?

With the example below,
https://google-developers.appspot.com/maps/documentation/javascript/examples/place-search
By using nearbySearch one of the place return is "John St Square Supermarket".
How do i generate a url to show "John St Square Supermarket" in full google maps?
Right now i'm generating by appending the latitude and longitude into "http://maps.google.com/?q=" which become something like http://maps.google.com/?q=123,456
but it won't show the place's name and the correct marker.
I then tried with http://maps.google.com/?q=John St Square Supermarket
Working good... until i stumble into a place name with multiple locations. For example,
http://maps.google.com/?q=SK%20Dato%27%20Abu%20Bakar
It shows multiple location but i only need one which i already know what it's latitude and longitude is.
You can add the Latitude and Longitude to the URL using the parameter ll:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471
You can also specify a default zoom level for the user using the paremeter z:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471&z=12
PlacesResult.url property stands for the url of Google Places.
https://developers.google.com/maps/documentation/javascript/reference#PlaceResult
So you can do like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Place Search</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script>
var map;
var infowindow;
var service;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId : google.maps.MapTypeId.ROADMAP,
center : pyrmont,
zoom : 15
});
var request = {
location : pyrmont,
radius : 500,
types : ['store']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map : map,
position : place.geometry.location,
reference : place.reference,
name : place.name
});
google.maps.event.addListener(marker, 'click', onMarker_clicked);
}
function onMarker_clicked() {
var marker = this;
service.getDetails({
reference : marker.get("reference")
}, function(result) {
var html = marker.get("name");
if (result && "url" in result) {
marker.set("url", result.url);
}
if (marker.get("url")) {
html = "<a href='" + marker.get("url") + "' target=_blank>" + html + "</a>";
}
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

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>