I was implementing google maps..And i want the default google blue dot for the current location. can anyone please tell, how to do so, in reactjs or in simple javascript..
First you have to allow the browser to send your Geo location to Google API, then wire up this code on the window/document load event :
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Hello World!',
icon: 'https://maps.google.com/mapfiles/kml/shapes/info-i_maps.png',
});
map.setCenter(pos);
}, function () {
//handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
//handleLocationError(false, infoWindow, map.getCenter());
}
}
Related
I added only Google Maps Script because it is the only part that does not work.
My issue is that I don't understand why the map does not see geolocation (my location). Visual Studio Code does not show any error and map loads but no geolocation. Unfortunately, I can't find the issue either.
<script>
var myStyles =[
{
featureType: "poi",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
function initMap() {
var artavenue = new google.maps.LatLng(59.441970, 24.784039),
myOptions = {
clickableIcons: false,
center: {lat:59.4370, lng:24.7536},
zoom: 12,
styles: myStyles,
disableDefaultUI: true,
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
infoWindow = new google.maps.InfoWindow;
markerA = new google.maps.Marker({
position: artavenue,
title: "Art Avenue 🍽️ 🍣 🍔 🥗 🍝 🍲",
icon:'art-avenue.png',
map: map
});
markerA.addListener('click', function(e) {
map.setCenter(this.position);
$(".modal-header .modal-title").text(this.title);
$(".modal-body #modalLatLng").text(this.position);
$('#myModal').modal('show');
});
markerA = new google.maps.Marker({
position: pointB,
title: "Marker A",
label: "A",
map: map
});
markerA.addListener('click', function(e) {
map.setCenter(this.position);
$(".modal-header .modal-title").text(this.title);
$(".modal-body #modalLatLng").text(this.position);
$('#myModal').modal('show');
});
}
I think that something goes wrong from here.
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Your position',
});
map.setCenter(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: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
It was because I was running page in localhost, thanks to Google Chrome inspect element console I saw the text that now they are not showing your location even if you are in the localhost. So there you go. When the page is live everything works.
I'm developing a web app with angular 6. I integrated google maps but marker click event is returning me an error.
Help me, thanks in advance.
import { } from '#types/googlemaps';
#ViewChild('whereMap') gmapElement: any;
map: google.maps.Map;
marker: google.maps.Marker;
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
let marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
}
map initialized and marker is working fine, but im unable to fire click event.
i have called the initMapp() in ngOnInit().
The navigator.geolocation.getCurrentPosition is asynchronous, you are likely meeting a race condition. You should move google.maps.event.addListener inside geolocation callback, otherwise you can try to assign event listener before the marker element was created.
Google Maps JavaScript API error message ERROR TypeError: Cannot read property '__e3_' of undefined typically means that you try to assign event to non-existing DOM element.
Try the following
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
this.marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
I hope this helps!
Hi I'm using google documentation in geocoding service.
The script should display the location Casablanca but it still show the default location in austalia
The problem is that geocoder.geocode(...) is not executed
function initMap() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
scrollwheel: false,
zoom: 8,
});
codeAddress(geocoder,map);
}
function codeAddress(geocoder, map)
{
var addr = "Casablanca";
geocoder.geocode( {'addr':addr}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.addr);//center the map over the result
//place a marker at the location
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.addr
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
PS:
I'm using GooglMapper https://github.com/bradcornford/Googlmapper
I appreciate any help.
geocoder.geocode( {'addr':addr}, function(results, status)
Should be:
geocoder.geocode( {'address':addr}, function(results, status)
The GeocoderRequest object literal contains the following fields:
{
address: string,
location: LatLng,
placeId: string,
bounds: LatLngBounds,
componentRestrictions: GeocoderComponentRestrictions,
region: string
}
Taken from the documentation
Answer For my problem
map.setCenter(results[0].geometry.addr);
Should be
map.setCenter(results[0].geometry.location);
And
position: results[0].geometry.addr
Should Be
position: results[0].geometry.location
I'm new to Google Maps Javascript API and doing some basic things. I want to show a day trip route of Yellowstone National Park. The start point is West Thumb Geyser Basin, end point is Norris Geyser Basin, as the code showing below (saved as a html file).
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function init() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng({lat: 44.427963, lng: -110.5906437}),// Yellowstone National Park
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: {lat: 44.4170394, lng: -110.5740972}, // West Thumb Geyser Basin,
destination: {lat: 44.7262344, lng: -110.7217907}, // Norris Geyser Basin,
travelMode: google.maps.TravelMode.DRIVING,
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<font size=2><b>Yellowstone National Parks</b></font>
<div id=googleMap style="width:1100px;height:800px;"></div>
</body>
</html>
But the route returned is not an optimal one.
Please see the returned route here
Seems it's a Google Maps JavaScript API bug? Any idea/thought? Thanks in advance.
Updated code. another funny thing. Without optimizedWaypoints, it's working fine.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function init() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng({lat: 44.427963, lng: -110.5906437}),// Yellowstone National Park
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var wayPoints = [{ location: {lat: 44.4604826, lng: -110.8303263}, stopover: true }, { location: {lat: 44.525086, lng: -110.840378}, stopover: true }]; // Old Faithful Geyser and Grand Prismatic Spring
directionsService.route({
origin: {lat: 44.4170394, lng: -110.5740972}, // West Thumb Geyser Basin,
destination: {lat: 44.7262344, lng: -110.7217907}, // Norris Geyser Basin,
waypoints: wayPoints,
//optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING,
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<font size=2><b>Yellowstone National Parks</b></font>
<div id=googleMap style="width:1100px;height:800px;"></div>
</body>
</html>
It is not going to be able to optimize the order of the waypoints (you only have one waypoint). The optimizeWaypoints option only rearranges the waypoints, it won't change the start or the destination.
from the documentation:
By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass optimizeWaypoints: true within the DirectionsRequest to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order. (This optimization is an application of the Travelling Salesman Problem.) All waypoints must be stopovers for the Directions service to optimize their route.
I have a 5 tab's app one of which contains a map.The map loads only when browsed to directly in the url bar.Otherwise it seems the controller is not loaded as i determined by some console logs. as the app will be run on mobile devices the map page will never be loaded first so i need a fix for this. I thought the controllers would be called when a tab is clicked but that doesn't seem t be the case.
Controller
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
//console.log("Map controller");
function initialize() {
var myLatlng = new google.maps.LatLng(43.07493,-89.381388);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//console.log('placing map');
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
$scope.map = map;
}
google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function(error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
})
View
<ion-view view-title="Directions">
<ion-content>
<div id="map" class="card" data-tap-disabled="true">
</div>
</ion-content>
</ion-view>
Tabs
<ion-tab title="Directions" icon-off="ion-ios-location-outline" icon-on="ion-ios-location" href="#/tab/directions">
<ion-nav-view name="tab-directions"></ion-nav-view>
</ion-tab>
Router
.state('tab.directions', {
url: '/directions',
views: {
'tab-directions': {
templateUrl: 'templates/tab-directions.html',
controller: 'MapCtrl'
}
}
})
please ask questions it there is more info i can give you.
I had the same issue. I execute the function when the view is entered.
I added google.maps.event.trigger( map, 'resize' ); after $scope.map = map; because the map only loaded after refreshing the view.
This is my controller:
.controller('MapsController', function($scope, $ionicLoading){
$scope.$on( "$ionicView.enter", function( scopes, states ) {
var myLatlng = new google.maps.LatLng(37.3000, -120.4833);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
navigator.geolocation.getCurrentPosition(function (pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
});
$scope.map = map;
google.maps.event.trigger( map, 'resize' );
});
});