Javascript Google Maps Api, multiple markers with links, only geoceder - javascript

I've got problems to put links on multiple markers, I can show my markers on the map, but when a I try tu put link on them, I have always the same link on all markers, the last. Here I provide a sample code:
<div id="map" style="height: 400px; width:100%;"></div>
<script>
var markers = [{"name":"Vasto","url":"http://www.google.com"},{"name":"Chieti","url":"http://www.wikipedia.com"}];
var geocoder;
var map;
var LatLng;
var url;
console.log(markers);
function initMap() {
LatLng = {lat: 42.2872297, lng: 13.3403448};
map = new google.maps.Map(document.getElementById('map'), {zoom: 8, center: LatLng});
geocoder = new google.maps.Geocoder();
setMarkers();
}
function setMarkers() {
var marker, i, url;
for( i = 0; i < markers.length; i++ ) {
url = markers[i].url;
geocoder.geocode({'address': markers[i].name}, function(results, status) {
if (status === 'OK') {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap" async defer></script>
Any solutions?
Thanks in advance

Due to asynchronous code, you need to change your code a bit
function setMarkers() {
markers.forEach(function(item) {
var url = item.url;
geocoder.geocode({'address': item.name}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}

Related

Clear Marker on Google Map when change location of dropdown

all. Please help me solve this issue. Currently I have a dropdown of multiple location for google map. But the marker keeps on duplicating when I change the location. Here is the code for google map. I would like the map to clear the previous marker and only display marker on the current selected location
var geocoder;
var map;
var marker;
function initMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(4.2105,101.9758),
zoom: 6.5
};
map = new google.maps.Map(mapCanvas, mapOptions);
geocoder = new google.maps.Geocoder();
google.maps.event.addDomListener(window, "load", initMap);
}
function geocodeAddress(location) {
var address = '';
if (location != 'all') {
var resultFromAjax = $.ajax({
type: 'POST',
url: "{{ route('getLocation') }}",
data: {
id: location
},
success: function (response) {
if (response.location != '') {
address = response.location;
}
},
error: function (xhr) {
console.log(xhr);
},
async: false
});
}
else {
address = 'Malaysia';
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
console.log(marker)
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
I have found the solution, instead of locally declare the marker, I set it as a global function before populate it based on location using geocoding.
var geocoder;
var map;
var marker;
function initMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(4.2105,101.9758),
zoom: 6.5
};
map = new google.maps.Map(mapCanvas, mapOptions);
geocoder = new google.maps.Geocoder();
//Marker
marker = new google.maps.Marker();
marker.setPosition(map.getCenter());
marker.setMap(map);
//
google.maps.event.addDomListener(window, "load", initMap);
}
function geocodeAddress(location) {
var address = '';
if (location != 'all') {
var resultFromAjax = $.ajax({
type: 'POST',
url: "{{ route('getLocation') }}",
data: {
id: location
},
success: function (response) {
if (response.location != '') {
address = response.location;
}
},
error: function (xhr) {
console.log(xhr);
},
async: false
});
}
else {
address = 'Malaysia';
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
marker.setOptions({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
// var marker = new google.maps.Marker({
// map: map,
// animation: google.maps.Animation.DROP,
// position: results[0].geometry.location
// });
console.log(marker)
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

How to display certain names in google maps infowindow marker

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>

Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api

doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
script(src='/javascripts/jquery.min.js')
script(src='http://maps.google.com/maps/api/js?key=AIzaSyD6MCxtDJOnbE1T6Y09k8Uca1rXHTQ3Bqg&v=3.exp&sensor=true&libraries=place‌​s')
script(src='/javascripts/global.js')
h1= title
#loading
p Loading your location
br
#map
input#my-address(type='text')
button#getCords(onclick='codeAddress();') getLat&Long
I write above code in jade template for display the map i.e 'index.jade' and
following file i.e 'global.js' is script file
//Calling the locateme function when the document finishes loading
$(document).ready(function() {
locateMe();
});
//Function to locate the user
var locateMe = function(){
var map_element= $('#map');
if (navigator.geolocation) {
var position= navigator.geolocation.getCurrentPosition(loadMap);
} else {
map_element.innerHTML = "Geolocation is not supported by this browser.";
}
};
//Lets load the mop using the position
var loadMap = function(position) {
var loading= $('#loading');
var latitude=position.coords.latitude;
var longitude=position.coords.longitude;
var myLatlng = new google.maps.LatLng(latitude, longitude);
//Initializing the options for the map
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//Creating the map in teh DOM
var map_element=document.getElementById("map");
var map = new google.maps.Map(map_element,myOptions);
//Adding markers to it
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'You are here'
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow({
content: "<h2>You are here:</h2>",
//Settingup the maxwidth
maxWidth: 300
});
//Event listener to trigger the marker content
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);});
};
//get lat and log
function codeAddress() {
alert('inside')
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var map = new google.maps.Map(document.getElementById("my-address"),{
center:pyrmont,
zoom:15
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow();
alert(infowindow);
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
};
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api
You are doing Place Search which doesnt return all of the fields that you are using:
http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses
In order to get the address, website, etc, you'll also need to call place.getDetails(), passing the Place's reference.
Below is a sample code snippet how to get Places details:
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}

Google maps infowindow error f = undefined infowindow.js

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>

Google maps zoom level for country

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

Categories

Resources