How to use google.maps.event.trigger(map, 'resize'); - javascript

I am new to JS and having challenges on resizing my google map. My problem: that only a third of my map is displaying and this is because a resize trigger needs to be implemented. My question: Where exactly do I correctly place the below trigger code within my script to implement it correctly.
Any help will be much appreciated
google.maps.event.trigger(map, 'resize');
Script:
<script type="text/javascript">
var map;
/*use google maps api built-in mechanism to attach dom events*/
google.maps.event.addDomListener(window, "load", function () {
/*create map*/
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng(51.506477,-0.071741),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
/*create infowindow (which will be used by markers)*/
var infoWindow = new google.maps.InfoWindow();
/*marker creater function (acts as a closure for html parameter)*/
function createMarker(options, html) {
var marker = new google.maps.Marker(options);
if (html) {
google.maps.event.addListener(marker, "click", function () {
infoWindow.setContent(html);
infoWindow.open(options.map, this);
});
}
return marker;
}
/*add markers to map*/
var marker0 = createMarker({
position: new google.maps.LatLng(51.506477,-0.071741),
map: map,
icon: "../../account/gallery/1700728/images/marker-red.png"
}, "<p>Saint Katharine's Way London E1W 1LD, United Kingdom</p>");
});
$(document).ready(function() {
$('#googleMap').css({'width':'100%','height':'380'});
google.maps.event.trigger(map, 'resize');
});
</script>

Related

Google maps v3 not a LatLngBounds or LatLngBoundsLiteral: not an Object name: "InvalidValueError"

Not the best with javascript and got some trouble with some google maps code but it is sporadic on MS Edge but consistent on Chrome and the markers will not load. On edge if you keep request the page sometimes it works but more than often fails.
ERROR: not a LatLngBounds or LatLngBoundsLiteral: not an Object name:
"InvalidValueError"
script is called using below code
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXX&libraries=places"></script>```
<script async type="text/javascript" src="{{media url='scripts/store-locator.js'}}"></script>```
require(["jquery"], function ($) {
$(document).ready(function () {
initialize();
});
var geocoder,
map,
markers = [],
infowindow = new google.maps.InfoWindow(),
bounds = new google.maps.LatLngBounds(),
marker, i;
var locations = [
{ id: 1, name: 'Store1', lat: 58.482514, lng: -1.784622 },
{ id: 2, name: 'Store2', lat: 54.687925, lng: 0.312584 }
];
function initialize() {
// set the default google map settings
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
var latlng = new google.maps.LatLng(52.727440, -1.543299);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// register the google map elements
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// register the directions display
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
addMarkers();
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
// setup control position
control = document.getElementById('store-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
control.style.display = 'block';
});
}
// add the markers from the array to the map
function addMarkers() {
$.each(locations, function (key, value) {
// create the marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(this.lat, this.lng),
map: map,
name: this.name
});
// add the marker to the cached array
markers.push(marker);
bounds.extend(marker.position);
// add the event listerner for the marker click function
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
// info window display
map.setZoom(16);
map.setCenter(marker.getPosition());
}
})(marker, i));
});
}
});```
Ok I think I have resolved it thanks to geocodezip who suggested a timing issue. was erroring on $(document).ready(function () {
initialize();
});
I've moved this to the bottom of the file and it seems to be running all good now..

How to create a moving marker in google maps

I a using Google Maps in my app.
The user is to be able to place a marker on any place in the map.
To this end I wrote the following code:
var marker;
function myMap() {
var mapCanvas = document.getElementById("map-canvas");
var myCenter=new google.maps.LatLng(50.833,-12.9167);
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
//marker.setMap(null); // this line does not work
placeMarker(map, event.latLng);
});
}
function placeMarker(map, location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
The marker is supposed to always move to the place where the user clicked.
The line
marker.setMap(null);
is supposed to remove the old marker (before the new marker is placed).
However, with this line in the code I cannot place any markers any more. Not including this line means that every marker stays in the map and is not removed (i.e. the map is filling up with markers over time).
Look at the javascript console, you will see Uncaught TypeError: Cannot read property 'setMap' of undefined. The first time, marker is null, you need to only set its map property to null if it already exists.
google.maps.event.addListener(map, 'click', function(event) {
if (marker) marker.setMap(null);
placeMarker(map, event.latLng);
});
proof of concept fiddle
code snippet:
var marker;
function myMap() {
var mapCanvas = document.getElementById("map-canvas");
var myCenter = new google.maps.LatLng(50.833, -12.9167);
var mapOptions = {
center: myCenter,
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) marker.setMap(null);
placeMarker(map, event.latLng);
});
}
function placeMarker(map, location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, "load", myMap);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
The problem is that you try to use method setMap after the first click when marker variable doesn't have this method. So, first check if marker has the method and then call it.
google.maps.event.addListener(map, 'click', function(event) {
// check if setMap is available and call it.
if(marker.hasOwnProperty('setMap')){
marker.setMap(null);
}
placeMarker(map, event.latLng);
});

Google maps api v3 not loading in maps

I have a problem with google maps, I have tried to just to set up a normal map, but nothing works all I get is this image:
And this is my code for this:
(function ($) {
var marker;
var map;
var iconBase = 'https://maps.google.com/mapfiles/ms/icons/';
var infowindow;
function initialize() {
getCoordinate(function (location) {
setUpMap(location.latitude, location.longitude);
});
}
function setUpMap(lat, long)
{
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 8,
center: myLatlng,
mapTypeControl: false,
streetViewControl: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress()
{
//Resellers is a global varaible that holds all the resellers addresses
Object.keys(resellers).forEach(function(key){
var reseller = resellers[key];
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(reseller.lat, reseller.lng),
icon: iconBase + 'green-dot.png'
});
(function (marker) {
// add click event
google.maps.event.addListener(marker, 'click', function () {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
title: key,
content: '<div style="color: black; height: 150px;">' + reseller.address + '</div>'
});
infowindow.open(map, marker);
});
})(marker);
gmaerksp.push(marker);
});
}
function getCoordinate(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
};
var location = returnValue;
callback(location);
}
);
}
google.maps.event.addDomListener(window, 'load', initialize);
}(jQuery));
#map-canvas{
width: 1200px;
height: 600px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
And I have no idea why the map is not loading, the markers is loading as it should. But as you can see, the zoom tools is not correctly loading either. So you guys have any idea what is wrong? I have tested with change the div size to but it still loads the same.
Well after more debugging, I found the answer! It seems like google maps can't be inserted with wordpress shortcode. I don't know why, but as soon as I move it out to it is own template instead it works like a charm.
So if any other persons have the same problem out there, and have put there google maps in a shortcode, try to move it out from there and see if it works.

How to show a map focused on a marker using a click event on Google Maps JavaScript API v3?

I created a map that focuses on a user's location. The map has a single marker with an info window. When a user clicks on the info window it gives him a hyperlink to an info page (info.html). I want to create an option that will allow the user to go back from the info page to the map, and the map should be focused on the same marker (not on his current location). It's basically going the opposite way. It sounds pretty simple, but I have no idea how to code this.
I guess I can build a different map for every marker, but that seems highly unlikely to be the right solution. Any help would be appreciated.
This is my attempt with the script, (initialize2() doesn't work):
$(document).ready(function() {
getLocation();
});
var map;
var jones = new google.maps.LatLng(40.59622788325198, -73.50334167480469);
function getLocation() {
navigator.geolocation.getCurrentPosition(
function(position) {
var myLatLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatLng);
},
function() {
alert("Please enable location detection on your device");
}
);
}
function initialize() {
var mapOptions = {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow({
});
var marker1 = new google.maps.Marker({
position: jones,
map: map
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow.setContent('<h4>Jones Beach</h4>See info');
infowindow.open(map,marker1);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// this is my attempt to focus on the marker
// there will be a button that will evoke this function from info.html
function initialize2() {
var mapOptions2 = {
zoom: 14,
center: new google.maps.LatLng(40.59622788325198, -73.50334167480469),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions2);
}
google.maps.event.addDomListener(window, 'load', initialize2);
What about using a hash in the url?
Try using "http://students.example.com/test.html#one":
$(function() {
var places = {
one: [40.59622788325198, -73.50334167480469],
two: [50.59622788325198, -71.50334167480469]
};
var div = $('#map-canvas');
var map = new google.maps.Map(div.get(0), {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = {};
$.each(places, function(name) {
markers[name] = new google.maps.Marker({
position: new google.maps.LatLng(this[0], this[1]),
map: map
});
});
var place = location.hash.substr(1);
if(place in places) {
map.setCenter(markers[place].getPosition());
}
});

Google Maps don't fully load

I have a somewhat strange problem. I have two maps on my site, a big one and a small one. I want to use the big one to show a route to a certain address. I'm now trying to implement the two maps but get a weird problem. The small map is working fine, but on the big map only a small area of the div is filled with the map, the rest is empty. (See the image.)
I use the following code to display the two maps:
function initialize() {
var latlng = new google.maps.LatLng(51.92475, 4.38206);
var myOptions = {zoom: 10, center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({position: latlng, map:map, title:"Home"});
var image = '/Core/Images/Icons/citysquare.png';
var myLatLng = new google.maps.LatLng(51.92308, 4.47058);
var cityCentre = new google.maps.Marker({position:myLatLng, map:map, icon:image, title:"Centre"});
marker.setMap(map);
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
jQuery(document).ready(function () {
[..]
initialize();
});
What's going wrong here?
EDIT:
Unfortunately the suggestions below doesn't seem to work. The closes i came is to remove the display:none from the elements and set the elements to hide with jquery
[..]
jQuery(document).ready(function () {
[..]
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).hide();
});
With the following result
Yes, #Argiropoulos-Stavros but, Add it as a listener
google.maps.event.addListenerOnce(map, 'idle', function(){
google.maps.event.trigger(map, 'resize');
map.setCenter(location);
});
It will begin re-sizing after, map rendered.
I think you are using v3.
So google.maps.event.trigger(map, "resize");
Also take a look at here
I fixed it!
I made an own function for the largemap and placed it in the callback when the elements are opened
function largeMap(){
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
$("#showRoute").click(function(e){
e.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeIn(500);
$("#shadowContent").show().css({'width':'750px','top':'25px','left':'50%','margin-left':'-400px'});
$("#closeBarLink").click(function(l){
l.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeOut(500);
});
largeMap();
});
Thanks anyway!!
call initialize(); function after you box active.
$(document).ready(function () {
$("#shadow").show(function () {
initialize();
})
});
When you're loading in the large map, try adding this at the end of your map code.
map.checkResize();
When Google Maps first renders on your page, it has the dimensions recorded so that it displays the map images in that size. If you're resizing the map dynamically, you need to tell the API to check the new size.
<script type='text/javascript' >
var geocoder, map;
function codeAddress() {
var address= '<?php echo $this->subject()->address; ?>';
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 13,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon:'http://rvillage.com/application/themes/rvillage/images/map-marker.png'
});
var infowindow = new google.maps.InfoWindow({ content: 'coming soon' });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
}
});
}
jQuery(document).ready(function () {
codeAddress();
});
</script>
You are using pop up window with jQuery, and I guest you call initialize() function when document is ready ( $(document).ready(function() {initialize(); }) ).
Try call initialize() function after pop up windown showed.
Johnny

Categories

Resources