Google maps, changing the map on click - outside the map - google-maps

I want to change the map (lat and lag) when a div (which is outside the map) is clicked.
I have got it working when the #map div is clicked, however any event outside the map does not get picked up.
This is what I have so far.
var map;
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.9722222,
lng: -3.1622222
},
disableDefaultUI: true,
zoom: 17,
mapTypeControlOptions: {
mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
'styled_map'
]
}
});
google.maps.event.addDomListener(mapDiv, 'click', function() {
window.alert('Map was clicked!');
});
var image = 'img/mapmarker.png';
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('styled_map', styledMapType);
map.setMapTypeId('styled_map');
var marker = new google.maps.Marker({
position: {
lat: 52.9722222,
lng: -3.1622222
},
map: map,
icon: image,
});
}

The map variable that is being initialized is local to the initMap function. You need to initialize the global version:
var map;
function initMap() {
var mapDiv = document.getElementById('map');
// remove the var before map in this line:
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 52.9722222, lng: -3.1622222},
proof of concept fiddle
code snippet:
var map;
function initMap() {
var mapDiv = document.getElementById('map');
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.9722222,
lng: -3.1622222
},
disableDefaultUI: true,
zoom: 17,
mapTypeControlOptions: {
mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
'styled_map'
]
}
});
google.maps.event.addDomListener(mapDiv, 'click', function() {
window.alert('Map was clicked!');
});
var marker = new google.maps.Marker({
position: {
lat: 52.9722222,
lng: -3.1622222
},
map: map
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" value="Click Me!" onclick="map.setCenter({lat:52.97,lng:-3.16});map.setZoom(15);" />
<div id="map"></div>

Related

custom google map doesn't show place details in KMZ file

I've a problem with my custom google map. It doesn't show street names .
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.753633, 13.952404),
zoom: 10,
mapTypeId: google.maps.MapTypeId.SATELLITE,
scrollwheel: true
}
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://128.199.209.42/klinkfiles/mlmsurvey.kmz'
});
ctaLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
<body onload="initialize()">
<div id="google-map" class="google-map"></div>
If you want the street names on the map tiles, don't request the SATELLITE map type, you want HYBRID.
var mapOptions = {
center: new google.maps.LatLng(42.753633, 13.952404),
zoom: 10,
mapTypeId: google.maps.MapTypeId.HYBRID,
scrollwheel: true
}
code snippet:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.753633, 13.952404),
zoom: 10,
mapTypeId: google.maps.MapTypeId.HYBRID,
scrollwheel: true
}
var map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://128.199.209.42/klinkfiles/mlmsurvey.kmz'
});
ctaLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#google-map {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="google-map"></div>

Not Able to Attach Drag & Dragend Events to Draggable Marker (Cannot read property 'addListener' of undefined)

can you pleas take a look at this code and let me know why I am not able to attach/bind drag and dragend events to the draggable marker?
I am getting
Uncaught TypeError: Cannot read property 'addListener' of undefined
on
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
lines
function initMap() {
var marker;
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
marker = new google.maps.Marker({
position: position,
draggable:true,
map: map
});
console.log(marker.position.lat());
}
function handleEvent(event) {
console.log(marker.position.lat());
}
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
}
You are adding the listener to the marker before it exists. Move those definitions into the placeMarker function.
function placeMarker(position, map) {
marker = new google.maps.Marker({
position: position,
draggable: true,
map: map
});
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
console.log(marker.position.lat());
}
proof of concept fiddle
code snippet:
function initMap() {
var marker;
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
marker = new google.maps.Marker({
position: position,
draggable: true,
map: map
});
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
console.log(marker.getPosition().toUrlValue(6));
}
function handleEvent(event) {
console.log(marker.getPosition().toUrlValue(6));
}
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

Marker not showing on Google Maps streetview if custom options is set

I've run into a strange problem if I include custom streetview options on Google Maps.
I have created a codepen to show the bug:
https://codepen.io/anon/pen/KyGByR
var map1,
map2;
function initialize() {
/* Map #1 */
var mapElement1 = document.getElementById('map1');
var mapOptions1 = {
zoom: 16,
center: new google.maps.LatLng(20.6726166, -100.3846899)
};
map1 = new google.maps.Map(mapElement1, mapOptions1);
var markerMap1 = new google.maps.Marker({
map: map1,
title: "Marker #1",
position: map1.getCenter()
});
/* Map #2 */
var mapElement2 = document.getElementById('map2');
var streetViewOptions = {
visible: false, //set to false so streetview is not triggered on the initial map load
fullscreenControl: false,
enableCloseButton: true,
addressControl: false,
addressControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
};
var street = new google.maps.StreetViewPanorama(mapElement2, streetViewOptions);
var mapOptions2 = {
zoom: 16,
center: new google.maps.LatLng(20.6726166, -100.3846899),
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.BOTTOM_CENTER
},
streetView: street
};
map2 = new google.maps.Map(mapElement2, mapOptions2);
var markerMap2 = new google.maps.Marker({
map: map2,
title: "Marker #2",
position: map2.getCenter()
});
}
google.maps.event.addDomListener(window, 'load', initialize);
In the first example, the marker will stay on the map if I turn on street view with the "street view icon".
In the second example, the marker will dissapear on the map if I turn on street view (but only in street view mode).
Any ideas on how to fix this?
You need to create a marker for the separate StreetViewPanorama
var markerMap2sv = new google.maps.Marker({
map: street,
title: "Marker #2",
position: map2.getCenter()
});
proof of concept fiddle
code snippet:
var map1,
map2;
function initialize() {
/* Map #1 */
var mapElement1 = document.getElementById('map1');
var mapOptions1 = {
zoom: 16,
center: new google.maps.LatLng(20.6726166, -100.3846899)
};
map1 = new google.maps.Map(mapElement1, mapOptions1);
var markerMap1 = new google.maps.Marker({
map: map1,
title: "Marker #1",
position: map1.getCenter()
});
/* Map #2 */
var mapElement2 = document.getElementById('map2');
var streetViewOptions = {
visible: false, //set to false so streetview is not triggered on the initial map load
fullscreenControl: false,
enableCloseButton: true,
addressControl: false,
addressControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
}
};
var street = new google.maps.StreetViewPanorama(mapElement2, streetViewOptions);
var mapOptions2 = {
zoom: 16,
center: new google.maps.LatLng(20.6726166, -100.3846899),
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.BOTTOM_CENTER
},
streetView: street
};
map2 = new google.maps.Map(mapElement2, mapOptions2);
var markerMap2 = new google.maps.Marker({
map: map2,
title: "Marker #2",
position: map2.getCenter()
});
var markerMap2sv = new google.maps.Marker({
map: street,
title: "Marker #2",
position: map2.getCenter()
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
#map1,
#map2 {
height: 50%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map1"></div>
<div id="map2"></div>

Cant get fitBounds to work

I'm not sure where to include the fit bounds as no matter where I put it, the map is centered on where initMap specifies which is halfway across the world instead of where the markers are.
Calls is just an object array that stores sets of lat/lngs
function initMap()
{
map = new google.maps.Map(document.getElementById('map'),
{
center: { lat: -34.397, lng: 150.644 },
zoom: 12,
scaleControl: true
});
}
// Place Markers on Map
function initMarkers()
{
for (var i = 0; i < Calls.length; i++)
{
var marker = new google.maps.Marker({
position: Calls[i],
map: map
});
}
}
function fit()
{
var bound = new google.maps.LatLngBounds();
for (var i in Calls)
{
bound.extend(Calls[i].getPosition());
}
map.fitBounds(bound);
}
// Initialize GoogleMap on Page Load
window.onload = function()
{
initMap();
initMarkers();
fit();
}
The posted code generates a javascript error (not the one originally reported in the question, but that has been removed): Uncaught TypeError: Calls[i].getPosition is not a function. Calls is an array of objects, so it won't have a .getPosition method.
function fit()
{
var bound = new google.maps.LatLngBounds();
for (var i in Calls)
{
bound.extend(new google.maps.LatLng(Calls[i].lat,Calls[i].lng));
}
map.fitBounds(bound);
}
code snippet:
var Calls = [{
lat: 42,
lng: -72
}, {
lat: 40.7127837,
lng: -74.0059413
}, {
lat: 40.735657,
lng: -74.1723667
}];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12,
scaleControl: true
});
}
// Place Markers on Map
function initMarkers() {
for (var i = 0; i < Calls.length; i++) {
var marker = new google.maps.Marker({
position: Calls[i],
map: map
});
}
}
function fit() {
var bound = new google.maps.LatLngBounds();
for (var i in Calls) {
bound.extend(new google.maps.LatLng(Calls[i].lat, Calls[i].lng));
}
map.fitBounds(bound);
}
// Initialize GoogleMap on Page Load
window.onload = function() {
initMap();
initMarkers();
fit();
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

How to use containsLocation() in DrawingManager

google.maps.event.addListener(drawingManager, "polygoncomplete", function (polygon) {
document.getElementById("cordinates").innerHTML = polygon.getPath().getArray();
google.maps.event.addListener(polygon.getPath(), "insert_at", function () { document.getElementById("cordinates").innerHTML =polygon.getPath().getArray(); } )
google.maps.event.addListener(polygon.getPath(), "remove_at", function () { document.getElementById("cordinates").innerHTML =polygon.getPath().getArray(); } )
google.maps.event.addListener(polygon.getPath(), "set_at", function () { document.getElementById("cordinates").innerHTML = polygon.getPath().getArray(); } )
I have that code part, I want to check some points inside of that polygon or not, but I have tried google.maps.geometry.poly.containsLocation(point, polygon)
that code but I have problem polygon, I do not know how to call that polygon from drawingmanager. I don't know to find polygon's reference from drawingmanager
The following example demonstrates how to utilize google.maps.geometry.poly.containsLocation function:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var sydneyLoc = new google.maps.LatLng(-33.868220, 151.201211);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
//google.maps.drawing.OverlayType.MARKER,
//google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYGON,
//google.maps.drawing.OverlayType.POLYLINE,
//google.maps.drawing.OverlayType.RECTANGLE
]
},
markerOptions: {icon: 'images/beachflag.png'},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
if(google.maps.geometry.poly.containsLocation(sydneyLoc, polygon) == true) {
document.getElementById('result').innerHTML = 'Sydney city is located inside your polygon';
}
});
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 320px;
}
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=drawing&callback=initMap"
async defer></script>
<div id="map"></div>
Info:<div id="result" />
I had the same scenario and fortunately I found the following working
Example
JavaScript
// This example requires the Geometry library. Include the libraries=geometry
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 24.886, lng: -70.269},
zoom: 5,
});
var triangleCoords = [
{lat: 25.774, lng: -80.19},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757}
];
var bermudaTriangle = new google.maps.Polygon({paths: triangleCoords});
google.maps.event.addListener(map, 'click', function(e) {
var resultColor =
google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle) ?
'blue' :
'red';
var resultPath =
google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle) ?
// A triangle.
"m 0 -1 l 1 2 -2 0 z" :
google.maps.SymbolPath.CIRCLE;
new google.maps.Marker({
position: e.latLng,
map: map,
icon: {
path: resultPath,
fillColor: resultColor,
fillOpacity: .2,
strokeColor: 'white',
strokeWeight: .5,
scale: 10
}
});
});
}
HTML
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=geometry&callback=initMap"
async defer></script>
CSS
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}