I'm new to javascript and I'm working on a project which needs to google maps.
I need to use the text search function to find nearby veterinary request a postcode does not work and I have several questions.
Do I need an API key to use the service places?
I Copied the code documentation google maps but don't understand the callback function and i don't know if something I'm doing is wrong.
If anyone has any idea what's wrong with the code, I would greatly appreciate your response.
This is my code:
<script src="https://maps.googleapis.com/maps/api/js?callback=ini&sensor=false&libraries=places"></script>
<script type="text/javascript">
var map;
var vet= " veterinarys";
ini();
function ini()
{
var mapOptions =
{
center: new google.maps.LatLng(37.7831, -122.4039 ),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var request =
{
radius: '500',
query: vet,
type: ['veterinary_care']
};
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]);
}
}
}
</script>
API key is optional, but you have to pay attention to this note.
The Google Maps JavaScript API does not require an API key to function correctly. However, we strongly encourage you to load the Maps API using an APIs Console key which allows you to monitor your application's Maps API usage.
Callback parameter in the script URL is required if you load resource asynchronously. In that case as soon as Google Maps script will be loaded it will call your function. In your case to start use it you should add async attribute to the <script> tag and remove direct ini() function call from the code. Here you find documented explanation for callback param
Your code doesn't work because you specify radius param which requires location to be specified as well. It should work if you will add the same location to the request object as center param in mapOptions. Just check available options description.
You got the rest of the help from #Mihails Boturins's answer. I will answer for the question you asked in your last comment.
There is no such createMarker function defined in you code. You have to create that function just like this
Related
Here is a link to the same question.
I would however like to have this question answered using Google Geocode.
Can someone please provide me with the code to do the following, using Meteor and Blaze.
Enter zip code and return array of zip codes within 10 kilometers of that zip code.
Search collection users for fields profile.zipcode and display users matching zip codes in the array.
Thank you very much!
The Geocoder gets you the location from the text string, now you have to pass this location information to your places functionality. I have wrapped the google places code inside a function and call it from geocoder.
var address = '12 Crest View Ct';
geocoder.geocode({'address': address},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK){
loc = results[0].geometry.location;
var bounds = new google.maps.LatLngBounds();
document.write(bounds.extend(results[0].geometry.location));
map.fitBounds(bounds);
new google.maps.Marker({
position:results[0].geometry.location,
map: map
});
place(loc); //here is the function call
}
}
);
When using Google Places API, what is the best way of hiding the map itself ?
We only need the search auto-complete, and our users don't need to see the map itself.
https://developers.google.com/maps/documentation/javascript/places?authuser=2#place_search_requests
Got the answer from https://developers.google.com/maps/documentation/javascript/places-autocomplete?authuser=2#video
Basically the Autocomplete constructor has a constructor overload
= new google.maps.places.Autocomplete( htmlInput, autoCompleteOptions )
var autocomplete = new google.maps.places.Autocomplete(input, { bounds: defaultBounds });
And this is not violating the TOS at all, reading the https://developers.google.com/maps/documentation/javascript/places-autocomplete?authuser=2#video above.
Having an issue with the results from the Google Maps PlacesService. The resultant PlaceResult object is now only returning one photo in the photos property array. In the past this was not the case and up to 10 photos were returned. Is this a change?
Example code:
var request = {
reference: place.reference
}
var callback = function(details, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
alert("Number of photos: " + details.photos.length);
}
}
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);
fiddle showing an example
In a previous answer that has been deleted I said that it must be a bug on the Google side.
I just found this issue :
https://code.google.com/p/gmaps-api-issues/issues/detail?id=6825&sort=-id&colspec=ID%20Type%20Status%20Introduced%20Fixed%20Summary%20Stars%20ApiType%20Internal
If I am right, the Google Maps PlacesService is the Javascript version of the Google Places API, so the backend code might be the same : that could explain why we have the same results (same bug(?)).
Hope this helps.
I have developed an application a while ago using GE plugin. In that application, I use the Geocode function which depends of course on (maps, 2.xx). With the deprecation of Google Maps V2, this part of the code is no longer working. My code is based on the sample application for geocoding in the Google Earth Demo site (http://earth-api-samples.googlecode.com/svn/trunk/examples/geocoder.html) which no longer works either.
I searched the v3 site but couldn't find a way of dealing with this. Using
google.load("maps", "3.xx");
instead of
google.load("maps", "2.xx");
simply doesn't work and I get a rejection from the Google Maps server.
The reason using google.load("maps", "3.xx"); doesn't work is that you MUST supply the sensor parameter. i.e. google.load('maps','3.6', { other_params: 'sensor=false' });
The sensor parameter of the URL must be included, and indicates
whether this application uses a sensor (such as a GPS locator) to
determine the user's location. We've left this example as a variable
set_to_true_or_false to emphasize that you must set this value to
either true or false explicitly.
See: https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API
Anyhow, I made a working example of using the Google Maps V3 Geocoder with the Earth Api for you to see how it works.
Also here is a code example that geocodes the term "New York" and moves to the first result found once the plugin and maps api have loaded (just in case jsfiddle disappears in future...)
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('earth', '1');
google.load('maps','3.6', { other_params: 'sensor=false' }); // or true
var ge = null; // GEPlugin
var geocoder = null; // GClientGeocoder
var init = function() {
google.earth.createInstance('map3d', initCallback, failureCallback);
};
var initCallback = function(object) {
ge = object;
geocoder = new window.google.maps.Geocoder(); //v3 Geocoder
ge.getWindow().setVisibility(true);
// for example: geocode New York
geocode("New York");
};
var failureCallback = function(error) {
alert("Plugin Error: " + error);
};
var geocode = function(address) {
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// do something with the result, such as flying to it...
var point = results[0].geometry.location;
var lookat = ge.createLookAt('');
lookat.set(point.lat(), point.lng(), 100, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 1000);
ge.getView().setAbstractView(lookat);
} else {
alert("Geocode Error: " + status);
}
});
};
google.setOnLoadCallback(init);
</script>
You could load the v3 script and modify the geocoding parts of your project, but if all you need is geocoding you can call the Geocoding web service directly.
Or, you can keep your existing code: Most old v2 code actually still works, it's just that GLatLng.x and y were never supported. So instead of point.x and point.y, use point.lng() and point.lat() respectively.
I've a layout template with a left sidebar where I show information of Location passed entities as an array.
Also in this template, I show a object Map with all of this locations.
I want to do click on a Location of my sidebar and then on the same template show another object Map replacing the previous with information of this Location. Keeping the sidebar with the information and not doing new queries on the database.
How to achieve this?
Ajax? Conditional layout?
I read this article but I don't understand how to solved my problem: http://twig.sensiolabs.org/doc/recipes.html#overriding-a-template-that-also-extends-itself
PD: I'm using Twig template and Symfony2
You could have a separate template for printing object map and, as you guessed, this would have to be done using AJAX. You would pass the data you want to show on map (not id as you don't want to query database again) and the controller would return formatted HTML.
However, this seems to me a bit overkill. I would always consider doing JS (with optional framework) in order to swap the content of sidebar with Map object.
It really depends on which map API do you use. If it could be controlled via JS I would look no further. It it could not, well then, AJAX is your natural choice....
UPDATE:
OK, what you should do is create initial Map object that will be modified later on:
var theMap = null;
function initializeMap(){
var mapOptions = {
center: new google.maps.LatLng(some_latitude, some_longitude),
zoom: 8, // goes from 0 to 18
mapTypeId: google.maps.MapTypeId.ROADMAP
};
theMap = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
// you must have some element with ID = 'map_canvas'
}
some_latitude and some_longitude are fairly unimportant as you will most likely set new coordinates in a few moments.
Now assuming (but not crucial at all) that you use some of the JS frameworks (I prefer jQuery) you could bind click event to those location links:
var onlyMarker = null;
$('.location').click(function(){
var $t = $(this);
var newLatLang = new google.maps.LatLng($t.attr('data-lat') ,$t.attr('data-lng'));
if ( onlyMarker == null ) {
onlyMarker = new google.maps.Marker({
position: newLatLang
map: theMap,
title: $t.attr('title')
});
}else{
onlyMarker.setPosition(newLatLang);
}
});
Now, relying on HTML5's 'data-*' attibutes is not good idea in particular as if you use any other version lower you will most likely end-up with invalid markup. The workaround is to for link (<a>) to carry id/key to LatLng object, for example:
// initially generated from `AJAX` or in `Twig` loop
var allLatlangs = [
new google.maps.LatLngf(some_latitude, some_longitude),
new google.maps.LatLngf(some_latitude, some_longitude),
new google.maps.LatLngf(some_latitude, some_longitude),
];
$('.location').click(function(){
var id = $(this).attr('id');
var newLatLang = allLatLang(id);
//....
// everything else is the same
// ....
});
Don't forget to include Maps API with proper API key:
https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&sensor=true
In order to obtain valid API key follow this link: API KEY HOW-TO
This link basically covers key steps that I have described here so study it and it should all come together nicely.
Also, if you're unsure how to retrieve some things from Maps you should consult reference:
REFERENCE which has every method call described pretty good
Remember not to execute any of this code until everything is being loaded.
Hope this helped a bit :)