I want to display on my webpage the location from a JSON that has displayed a pharmacy name. The point is that google maps API is a little bit over my power of knowledge. I did a find-place request into the google maps API, but the location that is displayed is the one from my current location.
Here is the part of the code that would interest you
<div id="map"></div>
<script src="./keys.js"></script>
<script>
let map;
document.addEventListener("DOMContentLoaded", () => {
let s = document.createElement("script");
document.head.appendChild(s);
s.addEventListener("load", () =>
{
console.log("script has loaded");
x = navigator.geolocation;
x.getCurrentPosition(success, failure)
function success(position){
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
var coords = new google.maps.LatLng(myLat,myLong);
map = new google.maps.Map(document.getElementById("map"), {
center: coords,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: coords,
})
}
function failure(){}
});
s.src = `https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=<%= "#{#medicament['farmacies'].first['name']}"%>&inputtype=textquery&fields=formatted_address,name,rating,opening_hours,geometry&key=**************`;
});
</script>
</div>
where <%= "#{#medicament['farmacies'].first['name']}"%> represents the name of the pharmacy from the html erb file.
What I found strange is that if I inspect the page where the location is the s.src takes me to a JSON that has all the right address information for the pharmacy.
Here you can see an image with the response from the API:
What I want is to point to the address of that pharmacy on google map. Any tips&tricks are very welcome!
Use google.maps.places.PlacesService.findPlaceFromQueryinstead.
Also see this tutorial.
var service = new google.maps.places.PlacesService();
var request = {
query: 'Museum of Contemporary Art Australia',
fields: ['name', 'geometry'],
};
const {results} = service.findPlaceFromQuery(request);
Related
First thing is I will tell you I am new to google maps and some of it is very confusing to me. What I need to do is show a users location and have the appropriate markers show up. I have the database all ready and somewhat of the Google map.
What I am working with is an example from here. What I can either get is the markers if I use a static LatLng or just the users dynamic location with no markers.
Need help please. And if you downvote this post please let me know why.
Code I am using can be found at https://jsfiddle.net/8q1apmdy/9/ and show where in the blow code is where I am missing something, most likely small or in the wrong position.
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
var map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 12
});
}
a) While running your code locally, I was getting 'pos' undefined, so I moved the following code 'var map = new google.maps.Map(..' inside the getCurrentPosition(){...
b) Then I got another error ' InvalidValueError: setMap: not an instance of Map;' so created a 'var map' globally.
Loaded the map successfully, but still markers were not loaded. while debugging your code at this point 'var marker = new google.maps.Marker({...' it is iterating for all markers from xml but somehow markers are not adding to the map..dont know the reason yet?
So I have tried in a different way. Please see all markers from xml displayed on map. Here I am just getting the 'name' in marker, you might need to add other parameters like id, address etc.
JSFiddle added for reference
var infowindow;
var map;
//var downloadUrl;
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-33.868820, 151.209290),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
downloadUrl("https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute('id');
var address = markers[i].getAttribute('address');
var type = markers[i].getAttribute('type');
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(latlng);
var marker = createMarker(id, markers[i].getAttribute("name"), address, latlng, type);
}//finish loop
//map.fitBounds(bounds);
}); //end downloadurl
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
}
function createMarker(id, name, address, latlng, type) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}
JSFiddle
I want to put in a street address, and have it programatically determine the coordinates and heading for the purposes of generating a street view map. instantstreetview.com does this, so I know it can be done. From the docs:
function initialize() {
var fenway = {lat: 42.345573, lng: -71.098326};
var map = new google.maps.Map(document.getElementById('map'), {
center: fenway,
zoom: 14
});
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
});
map.setStreetView(panorama);
}
Problem is, I don't know the heading of the address I want. Is there a simple way to achieve this?
You may want to look into getting the LatLng from the StreetViewLocation of the StreetViewPanorama rendered to compute the heading using the computeHeading() in the Geometry library in the Javascript API.
Take a look at this sample JSBin. I've created two Street View divs with the lat/lngs of two addresses across the street from each other. Notice that, regardless of the lat/lng, the same pano is returned, but there is no heading information, so the view is the same:
Now, look at this this modified JSBin. After computing the heading based on the StreetViewLocation.latLng of the panorama and lat/lng of the addresses passed into StreetViewService and using that as the pov for the panoramas, the correct Street View imagery is shown for each address:
The pertinent code:
var ll = new google.maps.LatLng(37.435292,-122.129517);
var svs = new google.maps.StreetViewService();
svs.getPanorama({location: ll, preference: 'nearest'}, function(data, status){
var pos = data.location.latLng;
var head = google.maps.geometry.spherical.computeHeading(pos, ll);
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('street-view'),
{
pano: data.location.pano,
pov: {heading: head, pitch:0}
});
});
EDIT: Adding another simple JSBin showing the use of the Geocoder to get the LatLng for the addresses: Pertinent code:
var ll;
var geocoder = new google.maps.Geocoder();
var svs = new google.maps.StreetViewService();
geocoder.geocode({address: "757 Moreno Ave Palo Alto, CA"}, function(results, status) {
if (status == 'OK') {
ll = results[0].geometry.location;
svs.getPanorama({location: ll, preference: 'nearest'}, function(data, status){
var pos = data.location.latLng;
var head = google.maps.geometry.spherical.computeHeading(pos, ll);
panorama = new google.maps.StreetViewPanorama(
document.getElementById('street-view'),
{
pano: data.location.pano,
pov: {heading: head, pitch:0}
});
});
}
});
I a using Google Places API Web Service, Google Maps Directions API for a project where I am using Google Place Autocomplete for my search query. As of I know, I am supposed to get 2500 requests per day. The project is in testing mode. I am sure I have not searched that limit, but still, I am getting a console error You have exceeded your daily request quota for this API.
I am unable to figure out. Can anyone please help me on this issue.
Thanks in advance.
I have added in footer
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=WeddinginitMap">
</script>
And my script is:
<script>
//Direction Grand Cruise
function initDirection() {
var $directionMap = $('[ data-directionMap ]');
$.each($directionMap, function( index, element){
var $dirEle = $(element);
var that = $(this);
var $id = $dirEle.get(0).id;
var $start = $dirEle.closest('.modal-content').find('.start-move').get(0).id;
var $end = $dirEle.closest('.modal-content').find('.end-move').get(0).id;
//console.log($end);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map($('#'+$id)[0] , {
zoom: 18,
center: {lat: 22.560941, lng: 88.354062}
});
var input = $('#'+$start)[0];
var autocomplete = new google.maps.places.Autocomplete(input);
directionsDisplay.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
$('#'+$start)[0].addEventListener('change', onChangeHandler);
$('#'+$end)[0].addEventListener('change', onChangeHandler);
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: $('#'+$start)[0].value,
destination: $('#'+$end)[0].value,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
});//end $.each
};// initDirection
</script>
<script>
function WeddinginitMap() {
var $locationSelector = $('.map-wrapper').find('.location-map[ data-map ]');
$.each( $locationSelector, function( index, element ){
var $ele = $(element);
var $this = $(this);
var $mapId = $ele.get(0).id;
var $lat = parseFloat( $('#'+$mapId).data('lat') );
var $long = parseFloat($('#'+$mapId).data('longi'));
var $zoom = parseFloat( $('#'+$mapId).data('zoom') );
console.log($mapId);
console.log($lat);
console.log($long);
console.log($zoom);
var uluru = {lat: $lat, lng: $long };
var $map = $('#'+$mapId)[0];
var map = new google.maps.Map($map, {
zoom: $zoom,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
icon:'assets/img/svg/vivada-ico.svg'
});
});//$.each
initDirection();
};
</script>
<script>
function initializeGoogletMapinsideModal(){
$('.map-modal ').on('shown.bs.modal', function (e) {
WeddinginitMap();
initDirection();
});
};
initializeGoogletMapinsideModal();
function redirectToDirectionModal(){
var $closeModal = $('.close-modal');
$.each( $closeModal, function(index, element ){
var $elem = $(element);
$elem.on('click', function(){
var $MainModal = $elem.closest('.map-modal');
var $targetDirectionModal = $elem.attr('data-target-modal');
$MainModal.modal('hide');
$($targetDirectionModal).modal('show');
$($targetDirectionModal).on('shown.bs.modal', function(e){
initDirection();
});
});//click
});//$.each
};
redirectToDirectionModal()
</script>
Places API has 1000 daily requests by default
https://developers.google.com/places/web-service/usage
You should be aware that each time when you are typing a new symbol in the autocomplete you are sending a new request. So it is quite easy to exceed 1000 quota using autocomplete element.
You can enable Billing in your project in order to get 150K daily requests for Places API free of charge.
Hope this helps!
Update
Please note that Google changes the behavior starting from June 11, 2018. They migrate to Google Maps Platform.
https://cloud.google.com/maps-platform/user-guide/product-changes/
From my observation, I did not see any usage from my dashboard
I played around the autocomplete list in the search box many times, but I still get no usage record. The quota counts only when one of the place options is selected. I searched through the document and API doc, there is no explanation on how exactly the autocomplete feature is counted. However, I do not agree that it counts as a new request every time user types in a single character. If it does, the quota (1000 per day) will be used up in few minutes and usage will reach the cap easily. Most apps cannot survive.
I would say the autocomplete is counted only when one of the items is picked.
I am trying to add geo-location to a custom public google map, I can't manage to get it to work. For example here is a custom public google map.
Lets say I wanted to add geo-targeting to that map. I have the following on the site which is directly off the google maps API website:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
as well as the following which I just changed '.getElementsById' to '.getElementsByClassName':
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementsByClassName('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Then I call for the map which is in a lightbox:
<h2 class="dis">Where can I<br />get Rumble?</h2>
It displays the map fine, and asks to geo-target but I assume the reason its not working on this map is because its not included in the API.
I was hoping someone had a solution for this.
This is not an API based map. You can display the KML from that map on an API based map
Then use your geolocation code to center the map (depending on the ordering, you might need to use the preserveViewport:true option on the KmlLayer). Relevant code below, see the documenation for more examples and information.
This is in your existing page (leave your version)
var myOptions = {
zoom: 5,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
Add this to display the data from your "custom map":
var kmlLayer = new google.maps.KmlLayer("https://maps.google.ca/maps/ms?ie=UTF8&msa=0&output=kml&msid=202458571791405992786.0004b9061a3fcd9461d42");
kmlLayer.setMap(map);
I am building a cycle information site and want to be able to grab the users location from their iPhone so i update my Google map and provide the user with relevant information. There is a Drupal module called Geolocation which uses the HTML5 option to do this and i have found the code which it is performing the task in the module below.
// START: Autodetect clientlocation.
// First use browser geolocation
if (navigator.geolocation) {
browserSupportFlag = true;
$('#geolocation-help-' + i + ':not(.geolocation-processed)').addClass('geolocation-processed').append(Drupal.t(', or use your browser geolocation system by clicking this link') +': <span id="geolocation-client-location-' + i + '" class="geolocation-client-location">' + Drupal.t('My Location') + '</span>');
// Set current user location, if available
$('#geolocation-client-location-' + i + ':not(.geolocation-processed)').addClass('geolocation-processed').click(function() {
navigator.geolocation.getCurrentPosition(function(position) {
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
Drupal.Geolocation.maps[i].setCenter(latLng);
Drupal.Geolocation.setMapMarker(latLng, i);
Drupal.Geolocation.codeLatLng(latLng, i, 'geocoder');
}, function() {
Drupal.Geolocation.handleNoGeolocation(browserSupportFlag, i);
});
});
}
Does anybody have any Google Maps API V3 experience of implementing this or similar? I would prefer the user to have to click "My Location" or equivalent to then use their iPhone's location to update the map rather than request it automatically. This is my Map and the array of markers that i have on it. How can i utilise the iPhones location to update it?
function initialize() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(51.51251523, -0.133201961),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
setMarkers(map, spots);
}
var spots = [
['Marylebone', 51.51811784, -0.144228881, '2.png', 2901, 'Broadcasting House - Marylebone</br>Available Bikes: 1</br>Number of Docks: 13</br> View more information about this dock'],
['Fitzrovia', 51.51991453, -0.136039674, '3.png', 2908, 'Scala Street - Fitzrovia</br>Available Bikes: 8</br>Number of Docks: 21</br> View more information about this dock'],
['Fitzrovia', 51.52351808, -0.143613641, '3.png', 2923, 'Bolsover Street - Fitzrovia</br>Available Bikes: 6</br>Number of Docks: 19</br> View more information about this dock'],
['Fitzrovia', 51.52025302, -0.141327271, '3.png', 2975, 'Great Titchfield Street - Fitzrovia</br>Available Bikes: 5</br>Number of Docks: 19</br> View more information about this dock'],
['Bloomsbury', 51.51858757, -0.132053392, '3.png', 2982, 'Bayley Street - Bloomsbury</br>Available Bikes: 12</br>Number of Docks: 25</br> View more information about this dock']
];
function setMarkers(map, locations) {
var image1 = new google.maps.MarkerImage('amber-spot.png',
new google.maps.Size(30, 36),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var spot = locations[i];
var myLatLng = new google.maps.LatLng(spot[1], spot[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: spot[3],
title: spot[0],
zIndex: spot[4],
html: spot[5]
});
bounds.extend(myLatLng);
map.fitBounds(bounds);
var infowindow = new google.maps.InfoWindow({
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.html);
infowindow.open(map,this);
});
}
}
thanks
Lee
First you will need a javascript function that will be fired from a button press, or a link click. This function will use the geolocation api available through html5 to check if the user can provide you with their location and grab it if so. The remainder of the function will use the google maps api to pan to that lat lng coordinate and set the zoom level appropriately.
Here is the google maps api map object which has the methods you need:
http://code.google.com/apis/maps/documentation/javascript/reference.html#Map
And this site has a great overview of basically everything you are trying to do:
http://www.html5laboratory.com/geolocation.php
Finally don't forget to save the location in your database or client side javascript array. If you are saving the data, warn the user of that for privacy implications.