I'm trying to do a script that locates the current position of the user and after reload of the page sets out a random coordinate. I can initilize the map and the random coordinate functions but the geolocation doesn't seem to locate my position, allthough it prints out the message in the infowindow?
var map;
var pos;
function initialize() {
//here is the starting for the map, where it will begin to show
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: "You are here"
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if (errorflag) {
alert('Geolocation not supported');
initialLocation = stockholm;
}
else {
alert('balblababa');
initialLocation = siberia;
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options, position);
}
//stop geolocation
var flagAreas = [
[59.2967322, 18.0009393],
[59.2980245, 17.9971503],
[59.2981078, 17.9980875],
[59.2982762, 17.9970823],
[59.2987638, 17.9917639],
[59.2987649, 17.9917824],
[59.2987847, 17.9917731],
[59.2988498, 17.991684],
[59.2988503, 17.9981593],
[59.3008233, 18.0041763],
[59.3014033, 18.0068793],
[59.3016619, 18.0137766]
];
var random = flagAreas.sort(function() {
return Math.random() - 0.5 })[0];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(random[0], random[1]),
map: map,
});
}
window.onload = initialize;
</script>
Thanks to Suvi Vignarajah.
Here is the working code!
var map;
var pos;
function initialize() {
//here is the starting for the map, where it will begin to show
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: initialLocation,
content: "You are here"
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if (errorflag) {
alert('Geolocation not supported');
initialLocation = stockholm;
}
else {
alert('balblababa');
initialLocation = siberia;
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options, position);
}
//stop geolocation
var flagAreas = [
[59.2967322, 18.0009393],
[59.2980245, 17.9971503],
[59.2981078, 17.9980875],
[59.2982762, 17.9970823],
[59.2987638, 17.9917639],
[59.2987649, 17.9917824],
[59.2987847, 17.9917731],
[59.2988498, 17.991684],
[59.2988503, 17.9981593],
[59.3008233, 18.0041763],
[59.3014033, 18.0068793],
[59.3016619, 18.0137766]
];
var random = flagAreas.sort(function() {
return Math.random() - 0.5 })[0];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(random[0], random[1]),
map: map,
});
}
window.onload = initialize;
Related
I have tried to make autocompletion for my application and show this to my Google maps but it doesn't works well.
The code is in a seperate js file called autocomplete.js
I already have a google maps in app so I want to use the same.
The id of google map is: googleMap
The id of search button is: autosearch
The id of input is: autoinput
"use strict";
var input = document.getElementById('autoinput');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
var input = document.getElementById('autoinput');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'be'}
};
function fillInAddress() {
var place = autocomplete.getPlace();
var defaultBounds = document.getElementById('googleMap')(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('autoinput');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
};
I changed code etc but i guess i deleted something that i need.
This is the other js file for geolocation called locationSearch.js:
var google;
$( document ).ready(function() {
zoekLocatie();
});
function zoekLocatie() {
var output = document.getElementById("googleMap");
navigator.geolocation.getCurrentPosition(success, error);
output.innerHTML = "<p>Looking for your location...</p>";
if (!navigator.geolocation) {
output.innerHTML = "<p>Your browser doesn't support geolocation</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var mapProp = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 18,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow);
function geocodeLatLng(geocoder, map, infowindow) {
var input = latitude + "," + longitude;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(18);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
address.innerHTML = results[1].formatted_address;
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
you have a error here
use strict";
you should remove the "
And where you call your google map function ?
I am trying to have places come up on the map based on the users geolocation. I know the geolocation works and map shows up, but none of the markers come up showing the local businesses. I am not getting any errors in console as well. I made sure that the script in my html is passing both the library and the API key, but just in case, here is the script:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_KEY"></script>
Here is my JavaScript...
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start 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: 'Found You!'
});
var request = {
location: pos,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
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]);
}
}
}
// Create Marker for Places
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);
});
}
// Google Maps Error Flags
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);
}
Here is my updated coded that I got to work.. I made some customizations to the markers, but this works now. As mentioned in the comments, I believe the issue had to do with the variables set for infowindow. I changed the geolocation one to 'infowindowLocation' instead and adjusted in the error flags section.
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start Geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindowLocation = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Found You!'
});
var request = {
location: pos,
radius: 3218.69,
types: ['dentist']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
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]);
}
}
}
// Create Marker for Places
function createMarker(place) {
var placeLoc = place.geometry.location;
var image = 'img/flag.png';
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name,
animation: google.maps.Animation.DROP,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map,marker);
});
}
// Google Maps Error Flags
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 infowindowLocation = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
initialize();
js:
var map;
function initialize() {
$('#refreshmap').on('click',initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
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);
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(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible:true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function(){
marker.setVisible(true);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html:
<div id="map-canvas"></div>
<button type="button" id="button" class="map_buttons button_style">Add marker</button>
The above code is for display marker on current location by clicking a button.Map is showing the current location but marker is not working.
I am getting this error in console "Uncaught ReferenceError: pos is not defined".
Try this:
var map;
var pos;
function initialize() {
$('#refreshmap').on('click', initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
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(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible: true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function () {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function () {
marker.setVisible(true);
});
}
Basically, declare var pos in the global scope, and remove var while initializing pos
The issue is that
During creation of the marker object, pos is undefined in the scope
try to declare pos global, like your map
var map;
var pos;
i want to make a google maps that shows the current location of the user and it should also be possible that the user can click on the map to add markers. i can do them separately but it fails when i try to combine them.
this is my code for the geolocation
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '500px';
mapcanvas.style.width = '600px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
and this is my code to add markers to the map.
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
check out the folllowing link..the example in it will help you surely.worked for me too.
http://www.codeproject.com/Articles/291499/Google-Maps-API-V3-for-ASP-NET
Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
var map;
var infowindow;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var 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]);
}
}
}
}
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() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Working code
var map;
var infowindow;
function initialize() {
var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var 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]);
}
}
}
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() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Any help if appreciated :)
Replace your line:
var latlon = new google.maps.LatLng
(position.coords.latitude + "," + position.coords.longitude);
with
var latlon = new google.maps.LatLng
(position.coords.latitude, position.coords.longitude);
The problem is in concatenating two values into one where constructor expects two parameters.