First of all, I just started with JavaScript, so I'm not really good at it. I am making an app, using the Google Maps Places API, in which you can push a button and get your location, push another button and get nearby places (for example stores or bars) based on your location. Getting the location of the device works, but my code doesn't display the nearby places. It does go to the location, but it doesn't show the markers of the nearby places. I don't know what is going wrong, but I think it might have to do with the code for the markers or with the sequence of the code.
I am using Intel XDK (HTML5 + Cordova and the App Designer) and the Google Maps Places API. Right now it all happens when one button (with id="myloc-btn") is pushed, but (if both the location and the nearby places work) I want to seperate them in two buttons, one to show the location and one to show the nearby places.
Below is my javascript code. I have commented out the marker for the location of the device I originally had, because I thought it might be in the way of the markers for the nearby places.
Anyone know what's wrong or can help me?
Thanks in advance!
---UPDATE---
I tried the search nearby places from the Google Maps documentation (https://developers.google.com/maps/documentation/javascript/examples/place-search), with a set location (I basically copied and pasted the code), but that doesn't work either. Again it goes to the right location, but it doesn't display any markers. I tried it both in the simulator and on my phone, but it both has the same result. I don't know why the markers don't show
var map;
var service;
var infoWindow;
var pos;
var marker = [];
//var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//var labelIndex = 0;
function register_event_handlers() {
$(document).on("click", "#myloc-btn", function(evt) {
initMap();
});
function initMap() {
map = new google.maps.Map(document.getElementById('gmap'), {zoom: 14});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
//addMarker(pos, map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var request = {
location: pos,
radius: 5000,
type: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
/*
function addMarker(location, map) {
var marker = new google.maps.Marker({
map: map,
// Define the place with a location, a query string and a label.
place: {
location: location,
query: 'This is my location'
},
label: labels[labelIndex++ % labels.length],
});
// Construct a new InfoWindow.
var infoWindow = new google.maps.InfoWindow({
content: 'Here I am!'
});
// Opens the InfoWindow when marker is clicked.
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
*/
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
document.addEventListener("app.Ready", register_event_handlers, false);
})();
In the callback provided to getCurrentPosition(), you're setting pos. However, this callback will get called after the phone has determined the location, i.e. at some random point in the future. Which is long after you're trying to use that pos in your request for the places. You need to move the places code in its own function, then call it while passing the map and pos, after you have centered the map. Almost exactly what you already did with addMarker().
Related
Using Google maps v3 API. When i visit the page with the map i sometimes get following error : "custom.js:46 Uncaught ReferenceError: google is not defined".
API's enabled on the key:
Google Maps Directions API
Google Maps Distance Matrix API
Google Maps Elevation API
Google Maps Geocoding API
Google Maps JavaScript API
When i reload the page, everything is working fine. This doesn't work 100% of the time. Multiple reloads are needed on some occasions.
I did notice that when the map isn't loading correctly this script is running in my head tags:
<script type="text/javascript" charset="UTF-8" src="https://maps.googleapis.com/maps/api/js/AuthenticationService.Authenticate?1shttp%3A%2F%2Fmayan-co.com%2Fen%2Foutlets&MYKEY&callback=_xdc_._h7cv8d&token=60166"></script>
After 10-20 seconds this script goes away and when i refresh the page after this script goes away, my map is working correctly.
Things i tried without results:
Putting the script to load the API in the footer.
Not using async or defer.
Adding specific url's to my api key.
Not using a api key
Loading the api script in the Head of my page:
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY" async defer></script>
My script to render the map and place markers on the map (loaded in the footer)
jQuery(document).ready(function($) {
$('#animation').addClass('animate');
$('.heart img').popover({
placement: 'top',
html: true,
container: '#animation',
content: function () {
return $(this).attr('alt');
}
});
$('body').on('click', function(e) {
$('.heart img').each(function() {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.heart img').has(e.target).length === 0) {
$(this).popover('hide');
} else {
$(this).popover('toggle');
}
});
});
function render_map($el) {
var $markers = $(document).find('#locations .data-source li');
var args = {
zoom: 16,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP]
}
};
var map = new google.maps.Map($el[0], args);
map.markers = [];
index = 0;
$markers.each(function() {
add_marker($(this), map, index);
index++;
});
center_map(map);
}
function add_marker($marker, map, index) {
var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));
var image = '../../img/maps-leaf.png';
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
map.markers.push(marker);
if ($marker.html()) {
$('#locations .data-display').append('<li class="linkage" id="p'+index+'">'+$marker.html()+'</li>');
$(document).on('click', '#p' + index, function() {
infowindow.open(map, marker);
setTimeout(function() { infowindow.close(); }, 5000);
});
var infowindow = new google.maps.InfoWindow({
content: $marker.html(),
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
function center_map(map) {
var bounds = new google.maps.LatLngBounds();
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
if( map.markers.length == 1 ) {
map.setCenter( bounds.getCenter() );
map.setZoom( 16 );
} else {
map.fitBounds( bounds );
}
}
$(document).ready(function(){
$('#map').each(function(){
render_map( $(this) );
});
});
});
What you describe looks like you try to instantiate the map before the Google Maps API JavaScript is loaded (you're using async attribute there). That's why it sometimes throws google is not defined error.
In other words, document.ready is called before https://maps.googleapis.com/maps/api/js?key=MYKEY is loaded.
Google Maps API allows you to use callback parameter in the URL with a name of a function that's called after the API is fully loaded. See https://developers.google.com/maps/documentation/javascript/tutorial.
So in your case you'll use URL like:
https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap
And then initialize the map:
initMap() {
var map = new google.maps.Map($el[0], args);
}
I want user's current location to be detected by browser and with predefined location from textbox or label that should calculate total distance between two places. It is something like zomato shows in any restaurant list. I want to know how can I do it for my vb.net website? Please suggest me any links which suggest this things.
to get the user's current location you'll need to use Geolocation API.
to get current Address from coordinates you'll need to use Geocoder API
To use Google Maps and these API you will have to generate an API Key for Google Cloud Platform. And make sure to enable the above mentioned API's for the generated API Key.
Example Code:
var map, infoWindow;
// initialize a map with given coordinates (call it in HTML!).
function initMap() {
var egypt = new google.maps.LatLng(26.8206, 30.8025);
infoWindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
center: egypt,
zoom: 6,
});
getCurrentLocation();
getCurrentAddress(map, infoWindow, pos);
}
// set Map to current location.
function getCurrentLocation() {
if (navigator.geolocation) {
// Browser supports geolocatin (get current location).
navigator.geolocation.getCurrentPosition(
function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here.');
infoWindow.open(map);
map.setZoom(15);
map.setCenter(pos);
getCurrentAddress(map, infoWindow, pos);
},
function () {
handleLocationError(true, infoWindow, map.getCenter());
}
);
} else {
// Browser doesn't support Geolocation.
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(
browserHasGeolocation
? // ? 'Error: The Geolocation service failed.'
'Error: Unable to get your current location.'
: "Error: Your browser doesn't support geolocation."
);
infoWindow.open(map);
}
// get current Address from coordinates (pos) using Geocoder API.
function getCurrentAddress(map, infowindow, pos) {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ latLng: pos }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
// create marker at current position.
const marker = new google.maps.Marker({
position: pos,
map: map,
});
// open an infoWindow above marker & set its content to current address.
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
console.log('Geocoding failed: ' + status);
}
});
}
}
#StupidRomeo Use Geolocation, Custom Controls, Autocomplete API(optional) , Distance Matrix Service.
Geolocation for attempting to locate the user's current user. Here is an example Note that this is upon accepting the user's that his/her location to known.
The Google Maps Geolocation API returns a location and accuracy radius based on information about cell towers and WiFi nodes that the mobile client can detect. This document describes the protocol used to send this data to the server and to return a response to the client.
An input box with (autocomplete api) helps ease the user's convience to find a correct location that Google Maps would find. Here is an example provided in the document. Using the autocomplete feature of the Google Places API to help users fill in the information.
Then lastly would be fetching the two point using the custom button and will call the Distance Matrix Service
Sample response of Distance Matrix Service API:
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 70778,
"text": "19 hours 40 mins"
},
"distance": {
"value": 1887508,
"text": "1173 mi"
}
}
I am trying to create with the google maps javascript api the following: After page loading a marker should become set at the users location, what now works. After that should where the user click on the map a marker become added and the previous one deleted. One marker should be only on the map. Now the previous marker wont become deleted and other become added what I dont want. What can I do to have always one marker on the map?
var markers = [];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 7
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
deleteMarkers();
addMarkers(event.latLng);
});
addMarkers(pos);
// Adds a marker to the map and push to the array.
function addMarkers(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
marker = [];
}
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
Take a look here I believe you are close :)
you are just setting your markers array to be nothing , but not actaully clearing the marker
I am working on a website that have multiple companies and employees, each company should register by entering its username,password and location on Google maps.
The location is going to appear to employees who are using an android application (Which is connected to the same website's database).
I want to know how to allow the company to specify their exact address either by typing the decimal points of the location or by using the pin to specify it on Google map or by allowing me to detect their location.
I read this: https://developers.google.com/maps/documentation/javascript/tutorial
but I do not know if it is what I need in my case.
Note that it is the first time for me to deal with maps so I am not deep into it.
I hope i understand you correctly.
One option could be something like this:
Get the user device' geolocation and put that position on a map with a draggable marker.
If the position is not correct, marker can be dragged and you will get the new coords - if the marker location has been changed.
Here is the code (with jquery):
var map;
var marker;
function initialize() {
var mapOptions = {
zoom: 11
};
map = new google.maps.Map(document.getElementById('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 marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Here you are',
draggable: true
});
$('#user-info').append('Location found using HTML5<br/>');
map.setCenter(pos);
google.maps.event.addListener(marker, 'dragend', function(a) {
$('#user-info').append(a.latLng.lat().toFixed(4) + ', ' + a.latLng.lng().toFixed(4) +'<br/>' );
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
$('#user-info').append('Error: The Geolocation service failed.');
} else {
$('#user-info').append('Error: Your browser doesn\'t support geolocation.');
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
};
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
http://jsfiddle.net/iambnz/xdoc1nxm/
I hope this will help you.
In case you will need to get the exact address, you have to add geocoding functionality.
My javascript isn't too hot, I'm trying to add a manual marker onto a number of locations gathered from the Google Places API.
I followed this post to get to my following code (with a few amendments):
<script type="text/javascript">
var map;
var infowindow;
var service ;
base_Icon_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.png";
shadow_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.shadow.png";
function initialize(lat,lng)
{
var origin = new google.maps.LatLng(lat,lng);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.HYBRID,
center: origin,
zoom: 14,
scrollwheel: false,
});
var request = {
location: origin,
radius: 2500,
types: ['train_station','bus_station','subway_station','airport']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
base_Icon_train = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
base_Icon_bus = "http://maps.google.com/mapfiles/ms/icons/green-dot.png";
base_Icon_subway = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
base_Icon_airport = "http://maps.google.com/mapfiles/ms/icons/yellow.png";
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker;
var icon_to_use;
if (place.types.indexOf('train_station') != -1) {
icon_to_use = base_Icon_train;
} else if (place.types.indexOf('bus_station') != -1) {
icon_to_use = base_Icon_bus;
} else if (place.types.indexOf('subway_station') != -1) {
icon_to_use = base_Icon_subway;
} else if (place.types.indexOf('airport') != -1) {
icon_to_use = base_Icon_airport;
}
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
var content='<strong style="font-size:1.2em">'+place.name+'</strong>'+
'<br/><strong>Latitude: </strong>'+placeLoc.lat()+
'<br/><strong>Longitude: </strong>'+placeLoc.lng()+
'<br/><strong>Type: </strong>'+place.types[0];
//make a request for further details
service.getDetails({reference:place.reference}, function (place, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
more_content='<hr/><strong>Details';
if(place.website)
{
more_content+='<br/><br/><strong>'+place.website+'';
}
}
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content+more_content);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', function(){initialize(<?php echo $coordinated; ?>);});
</script>
<div id="map" style="height:400px;"></div>
Now I would like to manually add another marker which is located at the center of the map (ie, the variable origin which is currently being pulled from a PHP variable - var origin = new google.maps.LatLng(lat,lng);). I also need this marker to have a different icon associated with it (base_Icon_festival and shadow_festival respectively).
I'm not sure how to manually add another marker to the ones already gathered by the places API?
End goal: have a festival icon marker at the center of the map and a number of public transport markers surrounding it, resulting code to go on individual festival pages of a website.
Thanks in advance to anyone who can help.
In the Google Maps API, markers are added to the map by creating a Marker object and setting the map property. This is the snippet in your code that adds the existing Markers.
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
To add a new marker you would just replace the position and icon properties with your values.
new google.maps.Marker({
map: map,
position: origin,
icon: shadow_festival
});
This code can probably be added at the end of the Callback function and if you don't need the actual marker object for anything else, you can just create the Marker object and never assign it.
There is an example from the Google Maps API docs here.