Googlemaps for Rails search for place - ruby-on-rails

Im using Gmaps4Rails gem in my rails app, so I just want to find out if it's possible to search for a place (I dont want to pass coordinates but name of country for example), so i need smth like on the pic below:

See the documentation: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Model-Customization
If you are doing a model based lookup, you would have your address in a field such as gmaps4rails_address. In your case, this would be simply the country.
You could have a boolean field called gmaps and set it to false, indicating that the address (country) has not yet been geocoded. Once it is geocoded, the lat & long will be stored in the appropriate model fields automatically, and the gmaps boolean will be automatically set to true so that the address is not geocoded again.
Update 1:
In response to your comment, your question is misleading. You said you wanted to pass the name of a country, which my solution does (e.g. the gmaps4rails_address field could contain 'Germany'). But it sounds like what you're looking for is to get a map outlining the boundaries of that country, which means you can't use the google maps api (it doesn't do that). So this gem (or any google maps gems) won't help you.
You need to use something like the Google Geomap javascript api. This can't be combined with a regular google map. The Geomap api will give you a flash map with the outlines of the countries.
From the documentation (https://developers.google.com/chart/interactive/docs/gallery/geomap):
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700]
]);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
</script>
</head>
<body>
<div id='map_canvas'></div>
</body>

Related

Find Near banks , schools from latitude and longitude using geocoder gem

I'm using geocoder rails gem. I want to find near banks , schools , hotels from some location.
location = Geocoder.search([48.856614, 2.3522219])
From above i can get location but not near important places.
How i can use near method of geocoder on "location" object, and find near places like hotels , schools and banks etc?
Any help?
Thanks
There is no filter or search as you describe in the Geocoder gem. You can get the nearest 10, 20, 50 other geocoded objects in your database.
So in order to make it function like you are describing you would need to Geocode each Hospital, School, Bank etc. and store them in a table, and then call nearbys on your point.
ie. Bulk geocode every Bank Listing within 500km in the location you are serving and check against that.
This method would quickly go stale and become ineffective. What you need is the Google Places API. They have a JS library you can leverage to get your results.
[Google Places JS API][1]
Text Search Requests The Google Places Text Search service is a web
service that returns information about a set of places based on a
string — for example "pizza in New York" or "shoe stores near Ottawa".
The service responds with a list of places matching the text string
and any location bias that has been set. The search response will
include a list of places. You can send a Place Details request for
more information about any of the places in the response.
I use the google api extensively and have found it remarkably easy to work with. Simply make a call to the API to retrieve an array of results for say, 'restaurant'. The example below is taken directly from the Google Developer page and will plot every restaurant in the Pyrmont area that they know about. The 'results' in the callback method will be a JSON object you can utilize with JS;
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}

Different google analytics tracking ID per subdomain

I created a new web property in my google analytics account. When I navigate to the Tracking Code of the property, the code looks like this:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-1');
</script>
I have multiple clients and each client has their own subdomain on my site. Example:
subdomain1.mysite.com UA-XXXXXXXXX-1
subdomain2.mysite.com UA-XXXXXXXXX-2
subdomain3.mysite.com UA-XXXXXXXXX-3
And in my HTML, I want to load the tracking code that that particular client has given me (identified based on current subdomain).
My question is, is it safe to assume, that the tracking code script will be the same for all the properties (except of course the UA number)?
If so, I can simply change the UA number in the tracking code like so:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= current_client.google_analytics_code %>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<%= current_client.google_analytics_code %>');
</script>
If you haven't made any other changes/additions to the tracking script (like custom dimensions, anonymizers, linkers, etc.) that you don't want pushed to all the clients' subdomains, then it is safe for you to dynamically insert the UA account ID.
Have in mind though, that if you plan to have two UA codes on those subdomains (for ex. your roll-up and theirs for the subdomain), you should rename trackers and cookies to separate the tracking and don't mix the attribution information between the accounts.

Google Tag Manager Twitter Universal Website Tag Event Parameters

I'm trying to implement Twitter conversion tracking using Google Tag Manager (GTM). In GTM there is a tag type of Twitter Universal Website Tag which has lots of extra purchase related parameters.
value : transaction price, usually in USD or GBP.
currency : e.g. GBP
order_id : e.g. INVOICE-5678
num_items : Number of items that were purchased.
content_ids : comma seperated list of item ids, ie. ['prod_1','prod_2','prod_3']
content_category : Category of the page or product
When I use the twitter pixel helper, none of these values is being registered even though they're being passed through from the dataLayer.
Does anyone know if Twitter uses these extra parameters when tracking conversions? I cannot see anything about in twitter GTM documentation.
I've been to this page:-
Twitter Help Page
And when it gets to the "For more information about tag events and required parameters, see the Twitter Help Centre".
The standard twitter conversion tracking code only allows for two params to be tracked.
tw_sale_amount and tw_order_quantity
Are these really the only parameters it takes?
I found that the GTM Universal Twitter Tag does work, but I had implimented the content_ids incorrectly. NOTE : If content_ids are not working for your twitter tag, it usually means your whole twitter tag is not working.
It needed to be a json_encoded array to work. All working correctly since I made this change. It also fixed my Facebook Tag integration.
<!-- language: lang-php -->
/* EXAMPLE */
$content_ids = [];
foreach ( $product_items as $product_item_data ) {
$content_ids[] = $product_item_data['product_item_sku'];
}
$tag_manager_data = array('content_ids' => json_encode( $content_ids ),
'price_data' => $price_data,
'currency' => $currency,
'item_count' => $item_count );
Then in your view / html file you can do the following:-
<!-- language: lang-js -->
<script>
var tag_manager_data = <?php echo json_encode( $tag_manager_data ); ?>;
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'value' : tag_manager_data.price_data,
'currency' : tag_manager_data.currency,
'content_category' : 'Checkout',
'content_ids' : tag_manager_data.content_ids,
'event' : 'InitiateCheckout'
});
</script>
Hope this helps someone. The above code is representative only and clearly needs more error checking.

How to get a Google Place ID from a Google GMS Address

I have seen previous posts regarding the conversion from a Google Place ID to an address; however I am interested in the opposite.
I have the GMS Address of the desired location but I want to acquire the Google Place ID in order to present more details to the user. From what I have seen on Google's iOS API website, you can attain a Google Place ID from an Autocomplete feature (for user searching), a selected location feature, or a current location feature.
My application intends to display multiple locations in which I already have the addresses for. The user can select individual locations for more details in addition to receiving details upon arrival. Therefore the features listed above are not ideal.
I have also tried using Google's Web API with features such as "Text Search Requests" & "Nearby Search Requests" however I am receiving "Zero Results".
Are there other methods that I haven't thought of and/or seen?
How about the Place ID finder in the Google Maps JavaScript API.
A place ID is a textual identifier that uniquely identifies a place. It is also available for most locations, including businesses, landmarks, parks, and intersections. These IDs are stable, meaning that once you've identified the place ID for a place, you can reuse that value when you next look up that place.
You can use the same place ID across the Google Places API and a number of Google Maps APIs. For example, you can use the same place ID to reference a place in the Places API, the Google Maps JavaScript API, the Google Maps Geocoding API, the Google Maps Embed API and the Google Maps Roads API.
Here is the sample code use for this.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
// Set the position of the marker using the place ID and location.
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location
});
marker.setVisible(true);
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address);
infowindow.open(map, marker);
});
}
Just take note that this example requires the Places library. Include
the libraries=places parameter when you first load the API. For
example:
script src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&libraries=places"

how to pass an array of object (Users in my case) to jQuery script from controller

I can't understand how to use variables initialized in the controller, for example, to jQuery script (autocomplete in my case). So I'm using Rails and get my authors list. How can I refernce them in jQuery script where I' d like to use jQuery autocomplete plugin like that:
[code]
$(document).ready(function() {
$("#book_author").autocomplete(url or data, options );
});
[/code]
So I should pass my authors array from the controler to the script. How to do that?
You can do it like this.
<script type="text/javascript">
var authors = <%= Author.find(:all).to_json -%>;
$(document).ready(function() {
$("#book_author").autocomplete(authors, options ); });
</script>
The Json string will be evaluated directly in JavaScript as an object.
The end result will in this case be something like
var authors = [{"author": {"id": 1, "name": "John"}}, {"author": {"id": 2, "name": "Jack"}}];
which will then be an array of objects easily handled in JavaScript.
To get it to work with autocomplete you'll probably have to do some more processing though to get it in the format it wants.
Just remember that the json string will include the model unless you've turned it off with
ActiveRecord::Base.include_root_in_json = false

Resources