I seem to have searched every SO question and the google maps api but can't see why my markers aren't showing up on my map. I've taken the code almost exactly from other areas and the console isn't showing any errors. This is my code
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
//set the geocoder
var geocoder = new google.maps.Geocoder();
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
//Function that gets run when the document loads
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(-31.954465, 115.859586);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Buggles marker location
var locations = [
['Test 1', -31.9522, 115.8589],
['Test 2', -31.1522, 115.4589],
['Test 3', -31.9322, 115.1589],
['Test 4', -31.5522, 115.9589],
['Test 5', -32.9522, 115.2589]
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
//geocode function
up206b.geocode = function()
{
var address = $('#location').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
$('#buggles-locations').removeClass('hidden');
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
and the example I followed included this in the body to load the function
<body onload="up206b.initialize()">
The example is here http://buggles.crushme.com.au/index.php Does anyone have any ideas why this might not be working?
Thanks
this code
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
value of i = max length of locations, you can save i to label of marker
marker = new google.maps.Marker({
position : myLatLng,
map : map,
title: i.toString(),
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(partInt(locations[this.getTitle())][0]);
infowindow.open(map, this);
});
Related
I have written code for Google Maps API where when I click a marker multiple markers should appear, but the marker that has been clicked should also appear. Means the page should not refresh. Please help me. Here is my code where if you click on the marker multiple markers will appear, but the marker disappears.
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap() {
var uluru = {lat: 25.2138, lng: 75.8648};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello World!',
map: map
});
marker.addListener('click', function() {
clicktoOpenMAp();
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
function clicktoOpenMAp() { var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.setTilt(50);
var markers = [
['chittorgarh', 24.8887, 74.6269],
['morak', 24.7265, 75.9739],
['mangrol', 25.3362, 76.5112]
];
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key='YourGoogleApiBecauseicantsharemine'&callback=initMap"></script>
</body>
</html>
Please use your Google API key, because I can't share mine.
Ok, this is how I fixed it:
function initMap() {
var uluru = {
lat: 25.2138,
lng: 75.8648
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello World!',
map: map
});
marker.addListener('click', function() {
clicktoOpenMAp();
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
function clicktoOpenMAp() {
// var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.mapTypeId = "roadmap";
map.setTilt(50);
var markers = [
['chittorgarh', 24.8887, 74.6269],
['morak', 24.7265, 75.9739],
['mangrol', 25.3362, 76.5112]
];
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
}
You were "creating" another map everytime you clicked in the marker (I commented the line so you know), then you need to put the Function clicktoOpenMap inside initmap.
Note: I also added async defer to the script where you call the api
<script
src="https://maps.googleapis.com/maps/api/js?key='YourGoogleApiBecauseicantsharemine'&callback=initMap" async defer></script>
You can hide the markers with
markers[i].setMap(null);
and to erase them
var markers = [];
I cannot drag marker of Google Map using JavaScript. Here is my code:
geocoder.geocode( { 'address': addrs}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#latitude').val(results[0].geometry.location.lat());
$('#longitude').val(results[0].geometry.location.lng());
var latitude=results[0].geometry.location.lat();
var longitude=results[0].geometry.location.lng();
var title=document.getElementById('googleMap').value;
var desc=title+","+address;
console.log(latitude,longitude);
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
// $window.addEventListener('load', onload, false);
// $window.onload = function () {
setTimeout(function(){
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.trigger(map, "resize");
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
google.maps.event.addListener(marker, 'dragend', function (event) {
var latdrag = this.getPosition().lat();
var longdrag= this.getPosition().lng();
console.log('latlong',latdrag,longdrag);
});
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(12);
}
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);
},2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
Here my issue is I am able to drag the marker but while I am dragging the new marker is coming to droppable place and the first one is still there. Here I need that single marker will only drag to any place and no new marker will create.
You are creating two markers in the same place and dragging the top one.
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
creates an array with two elements and in the loop, two markers are created.
I'm kind of stuck and was wondering if someone could help, here is a snippet of my code:
function test(person,address)
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker) {
//cant add information here dont know why...
return function() {
infowindow.setContent(person[0].cName + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker));
}
});
}//for
}//function
I'm passing an array of addresses and names. I've been trying to get each marker to display the person's name and address upon clicking on the infowindow of the marker on the map. This is where I'm having issues, I solved the address issue by just using the results[0].formatted_address but am unsure on how to display the specific user to that marker. Any tips would be appreciated.
You need function closure on the name as well as the marker in the click listener for the marker. As the name of the person needs to be available in the callback for the geocoder as well, you need function closure on the geocoder callback function as well.
Related questions
Google Maps V3 - I cannot reconcile closure
JS Geocoder cannot assign Global Variable for Google Maps Variable
proof of concept fiddle
code snippet:
function test(person, address) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address[i]
}, (function(name) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker, name) {
//cant add information here dont know why...
return function() {
infowindow.setContent(name + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker, name));
}
}
})(person[i]));
} //for
} //function
function initialize() {
test(["fred", "george", "frank"], ["New York, NY", "Newark, NJ", "Toronto, CA"]);
}
google.maps.event.addDomListener(window, "load", initialize);
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>
I've got a weird problem. It says f = undefined in infowindow.js. But I don't even have a file infowindow.js... This happens when I click on it. It has to show infowindow, but it doesn't.
Got the code from documentation here: LINK
Here's my code (address array is now adjusted, in my code there are normal addresses in it):
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 52.3, lng: 5.7 }
});
var geocoder = new google.maps.Geocoder();
var addresses = [
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
];
geocodeAddress(geocoder, map, addresses);
}
function geocodeAddress(geocoder, resultsMap, addresses) {
for(var i = 0; i < addresses.length; i++) {
geocoder.geocode({'address': addresses[i]['adres'] + addresses[i]['plaats']}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var counter = i - addresses.length;
var infowindow = new google.maps.InfoWindow({
content: 'test',
maxWidth: 200
});
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: 'testadres ' + addresses[counter]['plaats'],
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
i++;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
You use map instead of resultsMap in this piece of code:
The map object doesn't exist in this context. Should be:
infowindow.open(resultsMap, marker);
To close the staying infowindow before opening a new one, add only one infowindow instance and change it's content and position on marker click:
var infowindow = null;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 52.3, lng: 5.7 }
});
var geocoder = new google.maps.Geocoder();
var addresses = [];
geocodeAddress(geocoder, map, addresses);
}
function geocodeAddress(geocoder, resultsMap, addresses) {
var infowindow = new google.maps.InfoWindow();
for(var i = 0; i < addresses.length; i++) {
geocoder.geocode({'address': addresses[i]['adres'] + " " + addresses[i]['plaats']}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var counter = i - addresses.length;
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: 'testadres ' + addresses[counter]['plaats'],
});
marker.addListener('click', function() {
infowindow.setContent('test content');
infowindow.open(resultsMap, marker);
});
i++;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
<div id="map" style="height:400px; width:500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example