Custom Google Maps location hotlink - javascript

I have a custom map using the Google Maps API to navigate it, and I was looking into getting an address for hot-linking to the current location on the map (like the Maps link such as the following; http://maps.google.com/?ie=UTF8&ll=37.0625,-95.677068&spn=64.880423,135.263672&t=h&z=4 )
I'm not quite sure what the feature is called or how to go about this as I've yet to find anything relevant in the API documentation, does anyone know if this is doable with custom maps, and alternatively how to go about this/pointers on what I should be reading up on?

I've never seen it in the documentation and don't think it's possible. Been looking for it my self without luck.
You probably need to look on the url's query params and navigate to it with javascript.
Do this onload (let's presume that the var map is you google maps object):
var queryArray = window.location.search.substring(1).split('&'),
query = {},
parseQueryByKey = (function () {
var subQuery = '',
i = 0;
for (i = 0; i < queryArray.length; i += 1) {
if (queryArray[i] && queryArray[i].indexOf('=') !== -1) {
subQuery = queryArray[i].split('=');
query[subQuery[0]] = subQuery[1];
}
}
}());
// presumed url http://localhost/?lat=58.1323&lng=18.1231
if (window.location.search && 'lat' in query && 'lng' in query) {
map.setCenter(new google.maps.LatLng(parseFloat(query['lat']), parseFloat(query['lng'])))
}
Hope it helps.
..fredrik

Related

Google Feed API skipping articles?

With our without an API Key, the google feed api appears to be skipping some of the latest articles in the RSS queried.
Even the default example from https://developers.google.com/feed/v1/devguide?csw=1 appears to be skipping some articles whatever feed I use, see example here: http://codepen.io/anon/pen/xbxxwE
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
I'm specifically using this RSS, http://blog.ncb.org.uk/syndication.axd and the first 2 articles are not appearing either.
Is there anyone else using the API and experiencing the same issue? Where should we go from here? Is there some sort of support for the Feed API?
Cheers,
P.
Google caches the results and it may take up to an hour for it to refresh. That is why the latest articles wont show immediately.
Here was someone having similar issues of the feed not getting updated. It could be that maintaining the Feed API is not a high priority to Google any more. Yahoo Pipes or Superfeedr could be good alternatives.

Google analytic with iframe. Campaign tracking does'n work

I have problem with custom campaign tracking in Google analytic.
In sns my app embedded with inframe and all link looks like:
http://www.odnoklassniki.ru/game/tunerlife?utm_source=source1&utm_medium=Medium1&utm_campaign=CompName
but for iframe this param send like custom_args:
http://cdn.tuner-life.com/tl/frame_od.htm?authorized=1...custom_args=utm_source%3Dwork%26utm_medium%3Dwork1%26utm_campaign%3Dworkwork&session_...
in javascript i parse this param and push _setCampSourceKey and other 2 parameters like in a google documentation :
var custom_args = decodeURIComponent(flashvars["custom_args"]);
var custom_pairs = custom_args.split('&');
for (var i = 0; i < custom_pairs.length; i++)
{
var c_pair = custom_pairs[i].split('=');
if (c_pair[0] == "utm_source")
_gaq.push(['_setCampSourceKey', c_pair[1]]);
else if (c_pair[0] == "utm_medium")
_gaq.push(['_setCampMediumKey', c_pair[1]]);
else if (c_pair[0] == "utm_campaign")
_gaq.push(['_setCampNameKey', c_pair[1]]);
}
but i dont see my custom campaign in GA.
What wrong?
It looks like you're trying to change the key values but in reality you're changing the key names; don't do that. The utm_source keyname is still "utm_source" with a value of "work" but you're changing the keyname to "work", and theres no "work=work" in the URL so GA isn't recording a hit. Just delete that javascript code entirely.

Google custom search for images only

Since Google image search API is deprecated, one should use Google custom search API for this.
I've made a small example using it. My problem is I want to return google image search results only. Whereby this shows web results, and the user may switch to the image result. How can I show only the image results by default?
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'hu'});
google.setOnLoadCallback(function() {
var customSearchOptions = {
enableImageSearch: true,
imageSearchOptions: {
layout: google.search.ImageSearch.LAYOUT_CLASSIC
}
};
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
var customSearchControl = new google.search.CustomSearchControl('XXX', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
customSearchControl.setAutoCompletionId('XXX');
customSearchControl.draw('cse', options);
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
The API documentation is quite poor, it only describes how to add additional results.
Google images search is now supported in the Custom Search Engine API. See the API parameters section of this page. I'm using the API with python and for my application I just specify the parameter in the API call.
searchType = "image"
See this post on the cse blog.
EDIT: As Marc points out in his comment below, you need to click "Enable image search" in your CSE console.
Per the Google Custom Search Element Control API - documentation web site, this is possible.
https://developers.google.com/custom-search/docs/element
This is the fragment used for searching by image by default:
'defaultToImageSearch'
So I believe the full syntax for using this would be:
<script>
.
// Google custom search code, ids go here...
.
</script>
<gcse:search></gcse:search>
**<gcse:searchresults enableImageSearch="true" defaultToImageSearch="true">**
For those going through the WebExtensions tutorial, here's the updated code I used in popup.js to make it work with the new CSE functionality:
/**
* #param {string} searchTerm - Search term for Google Image search.
* #param {function(string,number,number)} callback - Called when an image has
* been found. The callback gets the URL, width and height of the image.
* #param {function(string)} errorCallback - Called when the image is not found.
* The callback gets a string that describes the failure reason.
*/
function getImageUrl(searchTerm, callback, errorCallback) {
// Google image search - 100 searches per day.
// https://developers.google.com/image-search/
// var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
// '?v=1.0&q=' + encodeURIComponent(searchTerm);
var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
'?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.items || response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
var firstResult = response.items[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.image.thumbnailLink;
var width = parseInt(firstResult.image.thumbnailWidth);
var height = parseInt(firstResult.image.thumbnailHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
Mainly it's changing the search URL (which should have searchType=image as mentioned) and the response structural references in getImageUrl, and setting up the CSE engine. Make sure your CSE has Image search turned on, and under Sites to search make sure to select Search the entire web but emphasize included sites from the options list.
I'm not 100% certain on this, but I don't think the API supports what you're trying to do. This is not at all surprising, as Google's search API's are infamous for being lacking in even basic functionality (such as the standard search API's limit of 20 results, etc). I think the fact that I'm the first person to answer this in the 3 days it's been active is another indication that this is probably just not supported (or, if it is, Google never bothered to tell anyone).
I know you're not going to like this, but I think your best option is to scrape the images out of the returned result set yourself. That's typically what people have to resort to when dealing with Google results data. Fortunately, their frontend code is remarkably consistent, so a few well-tuned regex matches and/or splits should do the trick for ya.
And yes, it's total BS that Google has provided such lousy support for this API. =)
Try adding this line:
customSearchOptions['disableWebSearch'] = true;
I tried to get a more authoritative answer in the official Google AJAX APIs group,
and it seems the answer is NO(!). Google custom search API currently does not support image search only. You can use the deprecated Google image search API instead.
check this
Try this one
customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;

How to make a "did you mean" link with suggestions, in google maps api?

I'm trying to make a web application with google maps api, that gives directions. Right now, It gives directions fine unless the user types in something wrong, it either doesn't show anything or it tries to figure it out and gives the wrong address. I want to make functionality where if the address is not recognized it has "did you mean" and then make a suggestion that's close to what you were trying to enter. I couldn't find anything in the google code that talked about that, but I'm wondering if anyone knows if it's possible, and how I can do it?
Thanks!
loadFromWayPoints() draws polyline only if the inputs provided to it maps to any definite point on the earth. You can avoid the confusion to function by fixing your from point in form of latitude and longitude, instead of address. Then using following function you may create Did you mean for To point if multiple points returned for toInput.
Code is self explanatory. If you dont understand. Reply in comment.
One of the point you want to plot should return definite point from google geocoder system.
In my I used the from point as definite point. And had it coordinates with me. So there is no chance of getting
geo.getLocations(toInput, function (result){
//map.clearOverlays();
if (result.Status.code == G_GEO_SUCCESS) {
// ===== If there was more than one result, "ask did you mean" on them all =====
if (result.Placemark.length > 1) {
document.getElementById("textualdirectionscontainer").innerHTML = "Did you mean:";
// Loop through the results
for (var i=0; i<result.Placemark.length; i++) {
var p = result.Placemark[i].Point.coordinates;
document.getElementById("textualdirectionscontainer").innerHTML += "<br>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"<\/a>";
}
}
// ===== If there was a single marker =====
else {
document.getElementById("textualdirectionscontainer").innerHTML = "";
var p = result.Placemark[0].Point.coordinates;
toLatLang = new GLatLng(p[1], p[0]);
// place(p[1],p[0]);
directionsPanel = $('textualdirectionscontainer');
directionsPanel.getElements('div').each(function(item) {
item.dispose();
});
directions.clear();
directions.loadFromWaypoints([hotelLatLng.toString(), toLatLang.toString()], {getPolyline:true});
/*var gp = directions.getPolyline();
map.addOverlay(gp); */
}
}
});

Center Google Map Based on geocoded IP

Basically whenever someones opens up my (Google) map I want it default to their approximate location.
Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?
You can use Google API's built-in ClientLocation object:
if (GBrowserIsCompatible())
{
var map = new google.maps.Map2(document.getElementById("mapdiv"));
if (google.loader.ClientLocation)
{
var center = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
var zoom = 8;
map.setCenter(center, zoom);
}
}
Check out http://www.ipinfodb.com/. You can get a latitude and longitude value by passing their services an IP address. I did something recently where I created a simple service that grabbed the current IP address and then passed it to the service ("api/location/city" is just a service that curls the ipinfodb service). Using jquery:
$.get("api/location/city", null, function(data, textStatus)
{
if (data != null)
{
if (data.Status == "OK")
{
var lat = parseFloat(data.Latitude);
var lng = parseFloat(data.Longitude);
$.setCenter(lat, lng, $.settings.defaultCityZoom);
manager = new MarkerManager(map, {trackMarkers : true });
var e = $.createUserMarker(map.getCenter());
e.bindInfoWindowHtml($("#marker-content-event").html());
var m = [];
m.push(e);
// map.addOverlay(e);
manager.addMarkers(m, 10);
manager.refresh();
}
else
{
$.setCenter($.settings.defaultLat, $.settings.defaultLng, $.settings.defaultZoom);
}
}
}, "json");
The key here is this line:
$.setCenter(lat, lng, $.settings.defaultCityZoom);
Just setting the center to the lat/lng of the result of the service call.
Per the docs, just map.setCenter(new GLatLng(37.4419, -122.1419), 13); or whatever other coordinates. Doing it in the page's Javascript is normally preferred.
If you mean translating an IP to lat and long, I don't think the Google API supports that, but there are other web services that do, such as maxmind, hostip, and many, many others. I don't know which one(s) to recommend -- try out a few, would be my suggestion!
If the user uses FireFox 3.5/google gears, you can retrieve the lat and lng from the browser itself.
You'll find details on another stackoverflow post here
IP Address Geocoding API for Google Maps: http://web3o.blogspot.com/2011/06/ip-address-geocoding-api-for-google.html

Categories

Resources