Google Maps: Passing extra arguments into GeoCoder for InfoWindows - javascript

This is my first post. I'm completely stuck and could use some help with adding infoWindows to Google Maps. The data I'm actually going to use (NOT the API I used here) doesn't have lat/lon and has multiple values.
Things are fine until infoWindow, but I can't pass any other arguments into the geocoder callback. Thanks in advance for the help!
Credit goes to Minghui Yu: http://goo.gl/zvAKZ8. Mine uses different data for the infowindow and will have probably about 30 markers.
Here's the relevant code JS FIDDLE:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker;
var i;
var mapData;
var locations = [];
$(document).ready(function () {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
async: false,
success: function (mapData) {
locations.push(mapData.name);
}
});
initialize();
});
function initialize() {
setMarkers(map, locations);
}
function setMarkers(map, address) {
for (var i = 0; i < address.length; i++) {
setMarker(map, address[i])
}
}
function setMarker(map, address) {
geocoder = new google.maps.Geocoder();
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({
position: results[0].geometry.location,
map: map
});
google.maps.event.addListener(marker,
"click", function () {
//HAVING THE PROBLEM HERE. Not sure how to separate this from the callback.
infowindow.setContent(mapData.main.temp);
// But this works if you run it:
//infowindow.setContent(address);
infowindow.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

You've declare myData as a global variable.
But here you have mapData as parameter of ajax success callback.
$(document).ready(function () {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
async: false,
success: function (mapData) { //locally scoped which can't override
locations.push(mapData.name);
}
});
This will not override the global variable.
Instead do like this
var gmapData = {};
and use it like
$(document).ready(function () {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk',
async: false,
success: function (mapData) {
locations.push(mapData.name);
gmapData = mapData; //assign mapData to global variable
}
});
Now use in infoWindow
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent() will accept only string
//whereas temp is numeric, so convert to string
infowindow.setContent(gmapData.main.temp.toString());
infowindow.open(map, marker);
});
JSFiddle

Related

Google markers not showing up

I want to use Google API to show route between A and B point and show all company's locations as marker. Showing route works well. But markers not displaying and showing no error.
Here is my code:
google.maps.event.addDomListener(window, "load", initMap);
function initMap() {
//create map
map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
ContextMenu = document.getElementById("my-context-menu");
google.maps.event.addListener(map, "rightclick", function (ev) {
currentLatLng = ev.latLng;
console.log(ev.latLng);
ShowContextMenuGoolge(ContextMenu, ev);
/** this stop NOT stopping DOM 'context-menu' event from firing */
ev.stop();
});
google.maps.event.addListener(map, "click", function () {
HideContextMenuGoolge(ContextMenu);
});
//create a DirectionsService object to use the route method and get a result for our request
directionsService = new google.maps.DirectionsService();
//create a DirectionsRenderer object which we will use to display the route
directionsDisplay = new google.maps.DirectionsRenderer();
//bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);
$.ajax({
type: "GET",
url: getAllMarkers,
success: function (res) {
createMarker(res);
},
err: function (err) {},
});
}
function createMarker(companies) {
// console.log(map);
companies.map((el) => {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(el.lat, el.lng),
map: map,
});
comMarkers.push(marker);
});
console.log(comMarkers);
}
This is result SS. Calculating route is works fine.
Thank for helping me.

Zoom to search (marker) position Google Maps API

I would like my map to zoom to the search (marker) position, when i search an address.
I have been looking through the forum and found advice but I cant get it to work.
Code sample
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 52.0, lng: 1.0}
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
map.setZoom(14);
map.panTo(Marker.position);
}
else {
alert('clever text here: ' + status);
}
});
Any ideas would be very much appreciated.
The setZoom(14) inside the geocodeAddress() function is not working since you have called it from an incorrect map object reference. You should call resultsMap.setZoom(14) instead of map.setZoom(14).
The "map" variable is declared inside the function initMap() and is passed as an argument when the geocodeAddress() function is called: geocodeAddress(geocoder, map).
Now in the method definition of geocodeAddress(), the map object reference is changed to "resultsMap" parameter name: function geocodeAddress(geocoder, resultsMap){...}. This is why you'll have to use resultsMap.setZoom(14) inside the geocodeAddress() function.
Here's a working sample in JSFiddle.
Hope this helps!

How to load google maps as callback?

I have defined an ajax function that get some records from the database, after the data was taken I want load google maps, so I passed the function as callback:
get_records = function (callback) {
var postUrl = "someurl";
var postData =
{
csrfToken: "token",
};
$.post(postUrl, postData, function (response) {
callback(response);
});
};
this is the callback:
get_records(function(result){
init_map();
});
where init_map is:
init_map = function () {
var map;
google.maps.event.addDomListener(window, "load", function () {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(33.808678, -117.918921),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
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;
}
var marker0 = createMarker({
position: new google.maps.LatLng(40.9117877, 14.7679659),
map: map,
icon: "../assets/img/marker-green.png"
}, "<h1 class='black-content'>Marker 0</h1><p>This is the home marker.</p>");
});
return map;
};
if I place the init_map function outside get_records the map is displayed, but with the code above I get no map displayed, why?
If there's no response coming from the ajax post, the callback will never be called.
A better approach is to use the Promise interface:
var jqxhr = $.post("example.php", function() {
console.log("success")
}).done(function() {
// call init_map() on done?
}).fail(function() {
// call init_map() on error?
}).always(function() {
// call init_map() regardless the response?
})
Also, you're using google.maps.event.addDomListener to add a listener during window load. If you're sure that your page is loaded before making the ajax post, you don't need this listener. You'll only need to create a new map inside the init_map function.

Repeating a function every x seconds

I am trying to repeat the function "refresh(geocoder, map, infowindow)" every x seconds but it won't work. Below is what the code that i have tried in html and javascript. Any help given is appreciated.
I am trying to repeat the function "refresh(geocoder, map, infowindow)" every x seconds but it won't work. Below is what the code that i have tried in html and javascript. Any help given is appreciated.
Thank you.
function initMap() {
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
myAddress = document.getElementById("address");
function refresh(geocoder, map, infowindow) {
$.ajax({
type: "GET",
url: 'http://localhost/scripts/retrievegeolocation.php',
dataType: "json",
success: function(data)
{
document.getElementById("Lat").innerHTML = data.Lat; // show response from the php script.
document.getElementById("Lng").innerHTML = data.Lng;
var latlng = {lat: parseFloat(data.Lat), lng: parseFloat(data.Lng)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(15);
var marker = new google.maps.Marker({
position: latlng,
map: map,icon:'http://localhost/img/car.png',
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
myAddress.innerHTML="Address: " + results[0].formatted_address;
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
});
}
<br/><center> LAT : <p id="Lat" name="Lat" value=" "></p></center><br/>
<center>LNG : </center>
<center><p id="Lng" name="Lng" value=" "></p></center>
<center><p style="font-size:20px;" id="address"></p></center>
<button onclick="function() {
refresh(geocoder, map, infowindow);
}">Try it</button>
It appears that you are missing a closing parenthesis for the function initMap()
I have removed all the code inside and called the dummy functions. It is working fine. Below is the code snippet. Copy paste this into browser console to run this.
function initMap() {
function refresh(geocoder, map, infowindow) {
alert(' refresh');
}
setInterval(refresh, 1000);
}
initMap();
Your button that is calling refresh(geocoder, map, infowindow) doesn't know what geocoder, map, or infowindow are. Two of those items are instantiated inside the initMap() function which is presumably the async loading Google javascript's callback function and map was never instantiated.
Assuming you have an element with the id of "map", put var map = document.getElementById("map"); close to the top of the initMap() function and then try adding this code within the initMap() function after you declare the refresh function.
setInterval( function() {
refresh(geocoder, map, infowindow);
}, 20 );

Reuse already loaded JavaScript

The goal
Reuse already loaded JavaScript correctly.
The problem
I'm generating a map dynamically using Google Maps API V3 and I need to reuse it. How?
The scenario
On Index.html, there's the following script:
var gMapsLoaded = false;
window.gMapsCallback = function () {
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function () {
if (gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0]
|| document.documentElement).appendChild(script_tag);
}
When I click on some button to show the map, my app invokes this script:
[...]
var geocoder;
var map;
var address = context.address();
function initialize() {
var mapDiv = document.getElementById("map_canvas");
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions:
{ style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapDiv, myOptions);
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{
content: '<b>' + address + '</b>',
size: new google.maps.Size(150, 50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
} else {
alert("No results found");
}
} else {
alert
("Geocode was not successful
for the following reason: " + status);
}
});
}
gMapsLoaded = false;
}
$(window).on('gMapsLoaded', initialize);
window.loadGoogleMaps();
As you can see, the application is always calling the loadGoogleMaps(); function that calls the external .js file. If I click in the 5 different maps, I get 5 scripts with the same proposal.
Someone have any idea to solve this?
Duplicated question?
Yes, I think that the essence of the question is duplicated, but the nucleus isn't.
As you can see, the application is always calling the
loadGoogleMaps(); function that calls the external .js file. If I
click in the 5 different maps, I get 5 scripts with the same proposal.
That is incorrect. After the first time it completely loads, the if statement on the first line will return early, preventing you from including it multiple times.
There's nothing wrong with the way that's written.
jsFiddle
var gMapsLoaded = false;
window.gMapsCallback = function () {
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function () {
if (gMapsLoaded) return window.gMapsCallback();
console.log('Generating new script tag');
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0]
|| document.documentElement).appendChild(script_tag);
}
$(window).on("gMapsLoaded",function(){
console.log("gMapsLoaded");
});
$(function(){
$("button").on("click",window.loadGoogleMaps);
});
Now, if you were to click it 5 times really fast when it isn't already loaded, it could potentially load it multiple times. You should call that function on it's own before a click event would normally happen to prevent that.
Update:
At the end of your initialize() method, you're using gMapsLoaded = false; which causes the above code to once again request a new script tag. Simply remove/comment out that line.

Categories