I'm trying to make part of my homepage dynamic where it will get the location object that is closest to your physical location.
I currently have a Location model with several fields including longitude and latitude. I would like to return the location model object that is closest to the longitude and latitude of the reader's ip address.
I have looked at the geo-kit gem, but it doesn't have Rails 3 support. I've also looked at the HTML5 geolocation, but it seems to only be client side (i.e. I get the lat and long of the user, but the page is already displayed). I'm assuming I could use ajax, but I'm not really familiar with it and there might be a less resource intensive way.
What is the best way to approach this?
My current code using the HTML5 geo-location is:
<script type="text/javascript">
function displayLocation(loc) {
var locDiv = document.getElementById("locationDiv");
locDiv.innerHTML = "lat: " + loc.coords.latitude + ", lon:" + loc.coords.longitude;
}
function initialize(){
var homeLocation = navigator.geolocation.getCurrentPosition(displayLocation);
}
</script>
<section class ="round">
<div id="locationDiv"></div>
</section>
Give this gem a try: https://github.com/chrisyour/geo_location
Related
I am trying to get the gradient information of the calculated route from here maps.
According to the documentation I need to add:
returnElevation = True
to cause "all shapes inside routing response to consist of 3 values instead of 2"
this was done here:
jsonAttributes: 1,
linkAttributes: 'sh,sl,ds',
routeAttributes: 'waypoints,shape,boundingBox',
legAttributes: 'boundingBox,shape',
maneuverAttributes: 'po,sh,rn,sp,rs,sa,sq',
returnElevation=true,
representation: 'turnByTurn',
later I receive the data with this:
var geo = links.shape[0].split(",");
latitudes.push(parseFloat(geo[0]));
longitudes.push(parseFloat(geo[1]));
altitude.push(parseFloat(geo[2]));
For some reason, this approach does not work, any Idea what I might be doing wrong?
Try replacing returnElevation=true with returnElevation:true, i think returnElevation=true will work directly in REST API request however javascript needs it with a ":"
I made a google Map and someone noticed that if you type, say "Brighton" into the search, it takes the user to the USA Brighton - what's desired is the UK's Brighton.
I went to the Google Docs page for it: https://developers.google.com/maps/documentation/javascript/localization#Region
And tried to amend my script url to:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=SECRET_KEY&callback=initMap®ion=GB"></script>
but performing the "Brighton" search still takes me to the USA.
What am I doing wrong? Tried in a private window to ensure it wasn't a cache thing ...
Although this script in particular loads the map on the page load, I have a function for searching the user's entered data which appeared like this:
# get lat lng values based on postcode / address
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='. urlencode($data['address']) .'&sensor=false&key=SECRET_KEY');
$geo = json_decode($geo, true);
Adding the ®ion=GB param here makes it work with user search.
# get lat lng values based on postcode / address
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='. urlencode($data['address']) .'&sensor=false&key=SECRET_KEY®ion=GB');
$geo = json_decode($geo, true);
I'm trying to make a client-side jquery request on an HTML page (in my Spring project) to the Google Places API so I can determine the ratings of a particular business type within a radius of x,y. At the moment I'm trying to do it like so:
function getCafe(){
$(document).ready(function(){
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
// These are lat long values calculated by the user's searched location on a google map on the client side
var Lat = marker.getPosition().lat();
console.log(Lat);
var Long = marker.getPosition().lng();
console.log(Long);
var cafeRatings = [];
// Ive disclosed my API Key
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=" + Lat + "," + Long + "&radius=500&type=restaurant&keyword=cruise&key=MY_API_KEY";
$.ajax({
type: "GET",
dataType: "xml",
url: url,
success: function(xml) {
$(xml).find('results').each(function(){
$(this).find("rating").each(function(){
var rating = $(this).text();
cafeRatings.push(rating);
});
});
//This is a simple debug to display the contents of the rating array to ensure the parse worked correctly
alert(cafeRatings.join("\n"));
}
});
});
}
However Michael Geary's answer to this question Google's Places API and JQuery request - Origin http://localhost is not allowed by Access-Control-Allow-Origin has lead me to believe I cannot use an Ajax jquery to access the API this way and I have to "use the Places Library from the Maps API V3. (As I) can't just hit a URL directly from JavaScript or jQuery code."
With that being said I've found the documentation to do this to be quite broad and resources online seem to be quite limited. Has anyone any experience on how to simply get the rating elements from the API stored into an array in JS so I can calculate the average and display it in a text box?
In case it's needed this how the XML formatted API looks
<PlaceSearchResponse>
<status>OK</status>
<result>
<name>Sydney Showboats</name>
<vicinity>32 The Promenade, Sydney</vicinity>
<type>travel_agency</type>
<type>restaurant</type>
<type>food</type>
<type>point_of_interest</type>
<type>establishment</type>
<geometry>
<location>
<lat>-33.8675570</lat>
<lng>151.2015270</lng>
</location>
<viewport>
<southwest>
<lat>-33.8689120</lat>
<lng>151.2001126</lng>
</southwest>
<northeast>
<lat>-33.8662141</lat>
<lng>151.2028105</lng>
</northeast>
</viewport>
</geometry>
<rating>3.8</rating> <------ This is the element im trying to ad to the array
<icon>
https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png
</icon>
<reference>
CmRSAAAALItuCtuLapozzsjq3dmKqj7NDik149XsgUwHD3ob5AWfHYlZtykuJbQa0cq0GMqX8dRgucTCmitnXgV-ekE3GfV7910rzHhx3ZuadVYNuWMzLDVZDCj2G1yiBw8r_hhgEhCPDXsniaZ2ZrkvYyXFfmQrGhSzdmkAEz4stXNx2qFe-GqAlldzgw
</reference>
<id>ce4ffe228ab7ad49bb050defe68b3d28cc879c4a</id>
<opening_hours>
<open_now>false</open_now>
</opening_hours>
<photo>
<photo_reference>
CmRaAAAAh4dP9hsZ_6515QNxouVnuYFYKemmf8BE01rcaOvkFlILQiwGNe_OAX0ikmobMmWZJvyjsFEsn7j1TFhauHSrek8nY5GsW24_6nwJsqEwHTUC10SL5gQITHhkdam50G1PEhCP-C7Of2mkjqJCTYFeYGWuGhQjVoWASHiGSp3WHm26Bh2sYOglZw
</photo_reference>
<width>2048</width>
<height>1152</height>
<html_attribution>
Sydney Showboats
</html_attribution>
</photo>
<place_id>ChIJjRuIiTiuEmsRCHhYnrWiSok</place_id>
<scope>GOOGLE</scope>
</result>
........
</PlaceSearchResponse>
My previous advice remains the same: you can't use the server-oriented web service version of the Places API. You have to use the JavaScript client library. It is much easier to use than the web service API (even if you were allowed to use that), because you don't have to parse any XML, just access the object properties that the client library provides.
There are several examples in the Places Library documentation. The Place Search example is fairly close to what you are doing. It looks like you want to access the rating for a place, and that is easy with the JavaScript library; simply use the rating property of your place object (or whatever name you give that variable).
I took the Place Search example and updated the fiddle to illustrate accessing the rating property. Try it out and see if it helps answer your question.
In any case, the bottom line is unchanged: you can't use the web service API, you need to use the JavaScript client library, but that is a Good Thing, as the client library does most of the work for you.
If the question is how to compute the average rating for the places you receive back from the API, that is simple: write a loop and do the arithmetic. If you look at the fiddle you will see where it has a loop that iterates over the results variable that the API callback receives. The loop in the fiddle creates a marker for each element of results, but you can do whatever you want there. Just add up all the rating values and divide the total by results.length and you have your average. Of course check that the length is nonzero, so you don't divide by zero.
For example, if you have a results variable with the array of places results, you could do:
var totalRating = 0;
results.forEach( function( place ) {
totalRating += place.rating;
});
var averageRating = results.length == 0 ? 0 : totalRating / results.length;
I noticed that there are a lot of these questions but I can't find something that relates to my particular project. I am building a Instagram and Google maps app. What I'm trying to do is I'm pulling all JSON format endpoints from Instagram with PHP. With Google maps, I'm adding the longitude and latitude coordinates that this certain API call passes through so you can see where the user has taken the photo at the time it was created. What I'm working on is using Google's event methods I am able to center longitude and latitude coordinates to the URL using the function parent.location.hash.
google.maps.event.addListener(map, 'center_changed', function(){
var control_center = map.getCenter();
var lng = control_center.lng();
var lat = control_center.lat();
parent.location.hash="&lng="+lng +"&lat="+lat;
$('.lng').append(lng);
console.log(map.getCenter());
console.log(lng +', ' +lat);
});
The issue I'm now running into is when I tried to retrieve lng and lat with PHP $_GET it was not working. I found out because it's a fragment and it never gets sent to the server. I found other tips and tricks like parse_url but that echos one string. Here is a snippet of what the current URL looks like when someone has done a search and moving Google maps around in the viewport -> api.php?location=houston#&lng=-95.34908043923292&lat=29.74942788453117.
The concept behind this API mashup is you have a search box, and you type in Houston, TX. Google maps will load and a feed from Instagram with display that have coordinates that are within Houston, Tx. The map will show where exactly where those photos taken. You move the map and we want more Instagram photos to show up but I can't pass the lng and lat variables to instagrams api. This is a bit of a long one, sorry.
Pastebin
can you try this and let me know,
$url=parse_url("http://domain.com/api.php?location=houston#&lng=-95.34908043923292&lat=29.74942788453117");
$myurl = $url["fragment"];
echo $myurl;
Update, to get individual variables
$url=parse_url("http://domain.com/api.php?location=houston#&lng=-95.34908043923292&lat=29.74942788453117");
$myurl = $url["fragment"];
echo $myurl.'<br>';
parse_str($myurl);
echo $lng.'<br>';
echo $lat;
So I am sure that there is a simple solution to my problem but I just can't seem to find an answer. I have an application that has two users place map markers onto a google maps map (and they can see eachothers markers). I want to find the average latitude and longitude and then use the Places API to get JSON that contains nearby locations from that average so the users can decide on a middle ground.
My problem is occurring with getting getting the JSON. Because it is cross domain I can't just use an AJAX call (and the API does not support jsonp). So I was hoping to do this client side in javascript. There are numerous tutorials out there for how to use the Places API when an actual map is on the screen, so how could I do this without the map and just the JSON data?
My application is using JavaScript, JQuery, and Java (a Jersey REST service). I read that there are ways to set up cross domain calls but those all seemed to apply to PHP.
If your application displays Places API data on a map, that map must be provided by Google.
If your application displays Places API data on a page or view that does not also display a Google Map, you must show a "Powered by Google" logo with that data. For example, if your application displays a list of places on one tab, and a Google Map with those places on another tab, the first tab must show the "Powered by Google" logo.
The following ZIP file contains the "Powered by Google" logo in the correct sizes for desktop, Android and iOS applications. You may not resize or modify these logos in any way.
Download: powered-by-google.zip
Read here: https://developers.google.com/maps/documentation/javascript/places#LogoRequirements
To use the Places library, just include the library in the API call and give the Places Service an HTML element instead of a map object:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
Code:
var request = {
location: new google.maps.LatLng(52.48,-1.89),
radius: '500',
types: ['store']
};
var container = document.getElementById('results');
var service = new google.maps.places.PlacesService(container);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
container.innerHTML += results[i].name + '<br />';
}
}
}
JSFiddle demo