Adjust Zoom Level if Geolocation is Successful? - javascript

How can I adjust the zoom level within the function if the geolocation is successful (success)?
function createMap(lat, lng) {
var mapOptions = { center: new google.maps.LatLng(lat, lng),
zoom: 12,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
function initialize() {
if(navigator.geolocation) {
success = function(position) {
createMap(position.coords.latitude, position.coords.longitude);
};
error = function() { createMap(99.648493, -99.410812); }
navigator.geolocation.getCurrentPosition(success, error);
}
}

Please check the following code to change zoom level based on geolocation:
function createMap(lat, lng, zoomVal) {
var mapOptions = { center: new google.maps.LatLng(lat, lng),
zoom: zoomVal,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
function initialize() {
if(navigator.geolocation) {
success = function(position) {
createMap(position.coords.latitude, position.coords.longitude,15);
};
error = function() {
createMap(99.648493, -99.410812,12);
}
navigator.geolocation.getCurrentPosition(success, error);
}
}

Related

add marker to the google maps in angular component

I am trying to add marker to the google maps.
but I am facing below error.
InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama
can you tell me how to fix it.
providing code and stackblitz below.
https://stackblitz.com/edit/angular-gmaps-api-suvdaf?file=src/app/map-loader.ts
return MapLoader.load().then((gapi) => {
this.map = new google.maps.Map(gmapElement.nativeElement, {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: type,
// label: "A"
});
this.map1 = new google.maps.Marker({
label: "A",
position: { lat: 59.33555, lng: 18.029851 },
map: map,
title: 'Hello World!'
});
// let markerSimple = new google.maps.Marker({
// label: "A",
// position: { lat: 59.33555, lng: 18.029851 },
// map: map,
// title: 'Hello World!'
// });
});
If i have understand your question this modified code will add markers
import { Injectable } from '#angular/core';
import { } from '#types/googlemaps';
declare var window: any;
// Credits to: Günter Zöchbauer
// StackOverflow Post: https://stackoverflow.com/a/39331160/9687729
#Injectable()
export class MapLoader {
private static promise;
map: google.maps.Map;
public static load() {
if (!MapLoader.promise) { // load once
MapLoader.promise = new Promise((resolve) => {
window['__onGapiLoaded'] = (ev) => {
console.log('gapi loaded')
resolve(window.gapi);
}
console.log('loading..')
const node = document.createElement('script');
node.src = 'https://maps.googleapis.com/maps/api/js?callback=__onGapiLoaded';
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
});
}
return MapLoader.promise;
}
initMap(gmapElement, lat, lng, zoom, type) {
return MapLoader.load().then((gapi) => {
this.map = new google.maps.Map(gmapElement.nativeElement, {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: type,
// label: "A"
});
//after map load add markers
this.createMarker();
});
}
createMarker() {
// list of hardcoded positions markers
var myLatLngList = {
myLatLng : [{ lat: 37.76487, lng: -122.41948 }, { lat: 59.33555, lng: 18.029851 }]
};
//iterate latLng and add markers
for(const data of myLatLngList.myLatLng){
var marker = new google.maps.Marker({
position: data,
map: this.map,
title: 'markers'
});
}
};
}

this.remove is not a function when removing Google Maps Overlay

I have an overlay placed on a google map:
function CustomerMarker(map) {
this.Map = map;
this.setMap(map);
}
GoogleMap = new google.maps.Map(document.getElementById("map"), {
zoom: 16,
canZoom: false,
center: { lat: lat, lng: lng },
mapTypeControl: false,
streetViewControl: false,
scaleControl: false,
clickableIcons: false
});
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.onAdd = function () {
//Some code
};
CustomMarker.prototype.draw = function () {
//Some code
};
CustomMarker = new CustomMarker(GoogleMap);
Which works fine, and the overlay shows up, however is issue arises when I try to remove that
CustomMarker.setMap(null)
I get an error and the marker remains
Error: this.remove is not a function
pz#https://maps.googleapis.com/maps-api-v3/api/js/30/1/overlay.js:1:251
rk#https://maps.googleapis.com/maps-api-v3/api/js/30/1/overlay.js:2:476
_.pg.prototype.map_changed/<#https://maps.googleapis.com/maps/api
/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:125:662
_.G#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:51:447
_.pg.prototype.map_changed#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:125:636
Db#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:37:103
_.k.set#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:101:728
_.jd/<#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:55:317
The documentation for OverlayView states:
You must implement three methods: onAdd(), draw(), and onRemove().
I don't see an implementation for onRemove.

Google Maps Javascript API not loading correctly

I am trying to load Google Maps API in a webpage with the <script> tags at the bottom of the body with the #map element referenced above.
Get the error alert: "This page was unable to display a Google Maps element. The provided Google API key is invalid or this site is not authorized to use it. Error Code: InvalidKeyOrUnauthorizedURLMapError"
My API KEY is definitely correct; I have checked it multiple times.
I have chosen to accept request from the following referrers
*.mywebsite.com/*
*.mywebsite.com*
www.mywebsite.com/*
www.mywebsite.com/test // this is the url I am trying to load the map on.
I have tried without the API Key Reference and without the Init callback and the map loads intermittently. Sometimes it will load (around 20% of the time), other times it doesn't and I get the following console log - ReferenceError: google is not defined;
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
<script src="/js/map.js"></script>
My map.js file containing the map config
var map;
var mapLatLng = {lat: 13.778182, lng: -0.23676};
var mapStyle = [maps style options] // https://snazzymaps.com/style/38/shades-of-grey
var mapMarker = '/img/marker.png';
function initMap() {
var styledMap = new google.maps.StyledMapType(mapStyle,
{name: "Styled Map"});
var mapOptions = {
center: mapLatLng,
zoom: 10,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var marker = new google.maps.Marker({
position: mapLatLng,
map: map,
title: 'Hello World!',
icon: mapMarker
});
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
google.maps.event.addDomListener(window, 'load', initMap);
You call the GMap script as async defer, so you are not sure that the script will be downloaded and executed before map.js. And your map.js script call the GMap API.
Could you test first without the async defer attribute. If it's ok, just move all your initialization code in the initMap function, it should work :
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: mapLatLng,
map: map,
title: 'Hello World!',
icon: mapMarker
});
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
var styledMap = new google.maps.StyledMapType(mapStyle, {name: "Styled Map"});
var mapOptions = {
center: mapLatLng,
zoom: 10,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
}

Google maps API (using gmapsjs), setCenter throws "undefined is not a function"?

I'm try to set map center using gmapjs. When I resize the window I get:
Uncaught TypeError: undefined is not a function
Here the map and the listener for the resize event:
$(function () {
var holder = $('#map-property'),
lat = 46.534820,
lng = 13.024809;
var map = new GMaps({
div: '#'+holder.attr('id'),
lat: lat,
lng: lng,
zoom: 14,
scrollwheel: false,
panControl : false,
streetViewControl: false,
mapTypeControl: false,
draggable: true,
disableDoubleClickZoom: true,
zoomControlOptions:{
style:google.maps.ZoomControlStyle.SMALL
}
})
.addMarker({
lat: 46.534820,
lng: 13.024809,
title: 'Da Matteo',
icon: "/img/gmaps-marker.png"
});
$(window).on('resize', function() {
map.setCenter(lat, lng); // here is the error!
});
});
AFAIK the setCenter function is:
this.setCenter = function(lat, lng, callback) {
this.map.panTo(new google.maps.LatLng(lat, lng));
if (callback) {
callback();
}
};
The problem is, map = new Gmaps().addMarker() returns a marker object, not a map. Therefore it has no setCenter method.
You can do something like:
var map = new Gmaps({...})
map.addMarker({...})
Then write the event.

add custom icons to google maps nearby places part2

got my current location with nearby places eg.(grocery_or_supermarket) and their icons.
but what i want to do is give each of the shops their own logo as an icon.
I'm new to JS so any help plz!
I have code to share if needed.
<script>
var infowindow,
placemarkers = [];
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
},
grocery_or_supermarket: {
icon: iconBase + 'convenience.png'
}
};
function placeSearch(map, request) {
var map = map;
var service = new google.maps.places.PlacesService(map);
service.search(request,
function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < results.length; ++i) {
bounds.extend(results[i].geometry.location);
placemarkers.push(createMarker(results[i].geometry.location,
map,
icons['grocery_or_supermarket'].icon,
results[i].name,
false, {
fnc: function () {
infowindow.open();
}
}));
}
map.fitBounds(bounds);
}
});
}
function createMarker(latlng, map, icon, content, center, action) {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: latlng,
content: content
});
////////toggle bounce////
google.maps.event.addListener(marker, 'click', toggleBounce);
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE); } } ///////bounce end////
if (icon) {
marker.setIcon(icon);
}
if (center) {
map.setCenter(latlng);
}
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
if (action) {
action.fnc(map, action.args);
}
return marker;
}
function initialize() {
var location = new google.maps.LatLng(-33.8665433, 151.1956316),
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: location,
zoom: 15,
});
infowindow = new google.maps.InfoWindow();
navigator.geolocation.getCurrentPosition(function (place) {
createMarker(
new google.maps.LatLng(place.coords.latitude,
place.coords.longitude),
map,
null,
'your current position',
true, {
fnc: placeSearch,
args: {
radius: 5000,
types: ['grocery_or_supermarket'],
location: new google.maps.LatLng(place.coords.latitude,
place.coords.longitude)
}
});
});
}
</script>
You can easily do with not so much code:
var iconBase = 'http://www.yourwebsite.com/';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: iconBase + 'myMarker.png' // Set yourt marker here
});
Here's is more about google maps and icons.
https://developers.google.com/maps/tutorials/customizing/custom-markers
Almost the same question, maybe can help you:
How to change icon on Google map marker

Categories

Resources