Reputation: 160
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>
Upvotes: 1
Views: 4716
Reputation: 31
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
Upvotes: 0
Reputation: 918
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.
Upvotes: 2