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

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.

Related

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.

Uncaught TypeError: Cannot read property 'apply' of undefined Google Maps

I am using Google Maps to make markers on a map and I am trying to convert addresses to geocodes using the following code:
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initialize" async defer></script>
<script type="text/javascript">
var map;
function initialize() {
var chamberLocation = {lat: 43, lng: -82};
var geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 42.9745, lng: -82.4066},
zoom: 14,
styles: [{"featureType":"road","elementType":"geometry","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"hue":149},{"saturation":-78},{"lightness":0}]},{"featureType":"road.highway","stylers":[{"hue":-31},{"saturation":-40},{"lightness":2.8}]},{"featureType":"poi","elementType":"label","stylers":[{"visibility":"off"}]},{"featureType":"landscape","stylers":[{"hue":163},{"saturation":-26},{"lightness":-1.1}]},{"featureType":"transit","stylers":[{"visibility":"off"}]},{"featureType":"water","stylers":[{"hue":3},{"saturation":-24.24},{"lightness":-38.57}]}],
zoomControl: false,
scaleControl: false,
mapTypeControl: false,
disableDefaultUI: false,
streetViewControl: false,
rotateControl: false,
scrollwheel: false,
draggable: false
});
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
var address = 'place';
geocoder.geocode({ 'address' : address }), function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
console.log('This didnt work' + status);
}
};
}
</script>
Whenever I do this I get an error saying Uncaught TypeError: Cannot read property 'apply' of undefined
What is causing this error? I am unsure as to how to fix this. Do I have to import another google maps api?
The error is a typo. I put the code below and commented //change in places where the typo was at. geocoder.geocode({}, callback) is a function that takes an object and a callback, but you have geocoder.geocode({ 'address' : address }), the typo is the ) it should be geocoder.geocode({ 'address' : address }, function(results, status) { ...
<div id="map" style="width: 320px; height: 480px;"></div>
<script type="text/javascript">
var map;
function initialize() {
// your code
// etc ...
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
var address = 'place';
geocoder.geocode({
'address': address
}, // change
function(results, status) {
if (status == 'OK') { // change
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
// some debug output
console.log("status is: " + status)
console.log("results is: " + JSON.stringify(results[0].geometry.location))
} else {
console.log('This didnt work' + status);
}
});
};
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initialize"></script>
Today i have also faced the same error while using distance matrix library, what we need to do is simply use the callback function mentioned here https://developers.google.com/maps/documentation/javascript/distancematrix
According to this doc https://developers.google.com/maps/documentation/javascript/examples/distance-matrix#maps_distance_matrix-typescript i was using promises thats when i encounterd the above error
var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087692, 14.421150);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: 'DRIVING',
transitOptions: TransitOptions,
drivingOptions: DrivingOptions,
unitSystem: UnitSystem,
avoidHighways: Boolean,
avoidTolls: Boolean,
}, callback);
function callback(response, status) {
// See Parsing the Results for
// the basics of a callback function.
console.log(status);
console.log(response);
}

Modernizr is not defined

I've included the Modernizr Touch Events detection to my project (only left the rest out to keep it light as possible).
I use it to set different Google Maps JS options as following:
<script>
function initMap() {
var myLatLng = {lat: 52.022322, lng: 4.209055};
if( Modernizr.touchevents ) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
disableDefaultUI: false,
center: myLatLng,
scrollwheel: true,
draggable: false,
});
} else {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
disableDefaultUI: false,
center: myLatLng,
scrollwheel: false,
draggable: true,
});
}
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Duijnisveld Kasconstructies',
});
}
</script>
I've included this script in my page-contact.php file which displays the contact page on my Wordpress project.
Whenever I view the page I see no map and note the following error in my console:
(index):235 Uncaught ReferenceError: Modernizr is not defined
What am I missing here?
Thanks guys!
You are calling Modernizr before theme-min.js which is where you are defining it.
You should move your code below this line.
<script type="text/javascript" src="http://duijnisveld.wpengine.com/wp-content/themes/duijnisveld-kascontructies/scripts/min/theme-min.js?ver=4.5.3"></script>

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']
}
};
}

Adjust Zoom Level if Geolocation is Successful?

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);
}
}

Categories

Resources