Google Maps infowindow don't work on marker click - javascript

I'm using Google Maps API v3 geocoding service. The geocoding part works fine. I type a zip code in a textbox and then hit the submit button. Then it shows a blue marker at the place which I typed in the textbox. And then it loads places in a radius of 20km and display these with a red marker. That all works fine. But then I got some problems with the infowindow.
If I click on a marker (red or blue) it happens nothing. And I just can't figure it out. I use this code for infowindow:
$.ajax({
url: 'data.php',
type: 'POST',
data: {xmldata: jqXHR.responseText},
success: function(locations, textStatus, jqXHR){
var split = locations.split(",");
var checkForDouble = split.filter(function(elem, pos) {
return split.indexOf(elem) == pos;
});
for(var i = 0; i < split.length; i++){
geocoder.geocode(
{'address': checkForDouble[i]},
function(results, status){
if(results != null){
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
}
);
var infocontent = checkForDouble[i];
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, infocontent) {
return function(){
infowindow.setContent(infocontent);
infowindow.open(map, marker);
}
})(marker, infocontent));
}
}
Can someone give me a hint where I made the error?

You need function closure on your geocoder call also.
var infowindow = new google.maps.InfoWindow();
function createMarker(address)
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infocontent = address;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(infocontent);
infowindow.open(map, marker);
});
return marker;
}
function geocodeAddress(address) {
geocoder.geocode(
{'address': address,
function(results, status){
if((results != null) && (status == google.maps.GeocoderStatus.OK)) {
var marker = createMarker(address);
} else alert("geocode failed on "+address+", status="+status);
}
);
}
$.ajax({
url: 'data.php',
type: 'POST',
data: {xmldata: jqXHR.responseText},
success: function(locations, textStatus, jqXHR){
var split = locations.split(",");
var checkForDouble = split.filter(function(elem, pos) {
return split.indexOf(elem) == pos;
});
for(var i = 0; i < split.length; i++){
geocodeAddress(checkForDouble[i]);
}
}

you have to use closure around your listener because it will use your parameter in future. you have to pass data to anonymous function.
With this code you can get your structure.
$.ajax({
url: 'data.php',
type: 'POST',
data: {xmldata: jqXHR.responseText},
success: function(locations, textStatus, jqXHR){
var split = locations.split(",");
var checkForDouble = split.filter(function(elem, pos) {
return split.indexOf(elem) == pos;
});
for(var i = 0; i < split.length; i++){
geocoder.geocode(
{'address': checkForDouble[i]},
function(results, status){
if(results != null){
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
}
);
(function (infocontent){
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow();
infowindow.setContent(infocontent);
infowindow.open(map, marker);
}
});
})(checkForDouble[i])
}
}

Related

Uncaught TypeError: Cannot read property 'targetLat' of undefined

well i just put some markers on google map and it works as i want and marker is displayed as required on the map but i get this error in the console i don't know why which makes the app runs on android but not on windows phone
function initMap() {
var map;
var faisalabad = { lat: 30.044281, lng: 31.340002 };
$('#locaitonBtn').click(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(latlng);
});
}
})
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: faisalabad,
disableDefaultUI: true
});
$.ajax({
async:false,
url: "https://someUrl",
method: "GET",
dataType: 'json',
success: function (data) {
var infowindow = new google.maps.InfoWindow();
for (i = 0; i <= data.targets.length; i++) {
var myLatLng = new google.maps.LatLng(data.targets[i].targetLat, data.targets[i].targetLong);
myMarker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: myLatLng
});
google.maps.event.addListener(myMarker, 'click', (function (myMarker, i) {
return function () {
infowindow.setContent(data.targets[i].targetName);
infowindow.open(map, myMarker);
}
})(myMarker, i));
}
}
})
}
$.ajax({
async:false,
url: "https://someUrl",
method: "GET",
dataType: 'json',
success: function (data) {
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i <= data.targets.length; i++) {
var myLatLng = new google.maps.LatLng(data.targets[i].targetLat, data.targets[i].targetLong);
var myMarker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: myLatLng
});
google.maps.event.addListener(myMarker, 'click', (function (myMarker, i, data) {
return function () {
infowindow.setContent(data.targets[i].targetName);
infowindow.open(map, myMarker);
}
})(myMarker, i, data));
}
}
});
changed 3 things:
var i = 0 in for statement
var myMarker = new google.maps.Marker ... (it's not a global)
injecting data to the anonymous click listener function because it has no scope on the data object.
i'm not sure this works because i have no test envoirement for it. but hope it helps you to figure out the failure.
i think the first point was the failure because you tried to use a global i in your for loop and reset it anywhere else in your code. so the array index returns undefined
Well I couldn't solve the problem or find an answer to it anywhere so i added the success function to a try catch block so it don't console the error and i can run the app now on windows phone

How to add pins to google map using jQuery and JSON

I am trying to add pins to a Google Map using postcodes stored in a Google Sheet. So far I have been able to access to the Postcodes in the spreadsheet using JSON:
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v) {
var data = $('<div class="listing">').append('<h4 id="bandb">' + v.gsx$postcode.$t + '</h4>');
$('body').append(data);
});
});
I am also able to add pins to a Google Map using the postcodes.
Example: http://codepen.io/aljohnstone/pen/eJOyrP
I am having trouble combining the two. I would like the postcodes variable in the Codepen to take the postcodes from my Google Sheet.
Working example using the Google Maps Javascript API v3:
$(document).ready(function() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: {
lat: 54,
lng: -3
},
zoom: 5
});
var i;
var postcodes = [];
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v) {
postcodes.push(v.gsx$postcode.$t);
});
}).done(function() {
map.setCenter(new google.maps.LatLng(54.00, -3.00));
map.setZoom(5);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < postcodes.length; i++) {
geocoder.geocode({
'address': "" + postcodes[i]
}, (function(i) {
return function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: postcodes[i]
});
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}
})(i));
}
});
});
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<div id="map_canvas"></div>
Try this
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false" type="text/javascript"></script>
<div id="map_canvas" style="width: 600px; height: 350px"></div>
<script type="text/javascript">
$(document).ready(function()
{
var geocoder = new GClientGeocoder();
var map = new GMap2(document.getElementById("map_canvas"));
var i;
var postcodes = [];
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json', function(data) {
$.each(data.feed.entry, function(i, v)
{
postcodes.push(v.gsx$postcode.$t);
});
}).done(function()
{
map.setCenter(new GLatLng(54.00, -3.00), 5);
for (i = 0; i < postcodes.length; i++) {
geocoder.getLatLng(postcodes[i] + ', UK', function(point) {
if (point) {
map.addOverlay(new GMarker(point));
}
});
}
});
});
</script>
Working example http://codepen.io/snm/pen/eJOVMY?editors=101

Laravel and Geocoding markers (nearby users) do not update correctly

I try to show on a google map markers that are near the current positon. If the map is dragged it will update the center coordinates and recalculate the markers around that center. The initial markers around the current users positon are showing correctly but when i drag the map they stay all the time the same. The update and the POST both is happening (my guess that the POST is not finished before the markers reload, so the old ones stay). The sourrounding markers are stored in a session variable.
Controller showNearbyUsers method:
/**
* Shows the users near the current one
*
* #return void
*/
public static function showNearbyUsers($centerlat,$centerlng)
{
try {
// Delete the session variable
if (Session::has('nearbies'))
{
Session::forget('nearbies');
}
// Define max, min for lat and lng
$centerlatlow = $centerlat-0.25;
$centerlathigh = $centerlat+0.25;
$centerlnglow = $centerlng-0.25;
$centerlnghigh = $centerlng+0.25;
$nearbies = DB::table('positions')->join('users', 'users.id', '=', 'positions.users_id')
->where('users_id', '!=', Auth::id())
->whereBetween('lat', array($centerlatlow, $centerlathigh))
->whereBetween('lng', array($centerlnglow, $centerlnghigh))
->select('positions.*', 'users.name', 'users.level')
->get();
if ($nearbies) {
return Session::put('nearbies', $nearbies);
}
} catch(\Exception $e) {
Session::flash('message', 'An error occured with your localization. Enable GPS and refresh.');
Session::flash('alert-class', 'alert-danger');
}
}
View Script
<script>
// Auto adjust map div
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 220; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
// Setup token security
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
// Attributes
var map;
var geocoder;
var markers = Array(); // Contains x,y
var users = Array(); // Contains whole user info
var current = Array();
var infoWindows = Array();
var mapCenter;
// Test initialize users array
//users = [['Brugg',47.47963,8.18465],['Aarau',47.39340,8.04312],['Baden',47.47377,8.30647]];
// Initialize the map with logged in user
function initialize() {
geocoder = new google.maps.Geocoder();
getLocation();
}
// Set nearby user markers
function setMarkers(list) {
for(var i=0; i<list[0].length; i++){
var element = (list[0])[i];
var nearbyLatLng = new google.maps.LatLng(element['lat'], element['lng']);
console.log((list[0])[i]);
markers[i] = new google.maps.Marker({
position: nearbyLatLng,
map: map,
title: element['name'],
infoWindowIndex : i
});
infoWindows[i] = new google.maps.InfoWindow({
content : element['name']
});
google.maps.event.addListener(markers[i], 'click',
function(event)
{
infoWindows[this.infoWindowIndex].open(map, this);
}
);
}
}
// Delete nearby user markers
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
// Map dragging listener. Updates the nearby users markers
function mapDragListener() {
google.maps.event.addListener(map, 'dragend', function() {
deleteMarkers();
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
#if(Session::has('nearbies'))
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
console.log(users);
#endif
setMarkers(users);
});
}
// Map zoom listener. Updates the nearby users markers
function mapZoomListener() {
}
// Get current user location
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
// If success in finding current position
function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Send to geocoordinates.php and save to DB
$.post("updateme/"+lat+"/"+lng);
mainMapCalc(lat, lng);
}
// If no success in finding current position
function geoError() {
alert("Please enable Geo-Location and Refresh the Website.");
}
// Set the logged in users and build up the environment
function mainMapCalc(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[1]) {
//formatted address
var address = results[0].formatted_address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 18,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
setMarkers(users); // Set initial nearby markers
mapDragListener(); // Register Listener
//mapZoomListener(); // TODO: Register Listener
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
} else {
alert("Geocoder Error// No results found");
}
} else {
alert("Geocoder Error// Failed due to: " + status);
}
});
}
// Show Map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Where is here the problem?
Thanks in advance
It looks like the problem is that you are sending out the ajax request, but you are not doing anything with the returned data. Try changing
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
to
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
success: function(data, textStatus, jqXHR) {
// request succeeded
// data - response from server
},
error: function (jqXHR, textStatus, errorThrown){
// the request failed
}
});
Also note that async: false is deprecated: https://api.jquery.com/jQuery.ajax/#options, so you should use callbacks as shown above.

Mark multiple locations in Google Map

I am using Google map api v3 to plot markers of location array. My script is
function OnSuccess(response) {
var markers = response.d.split('^^');
var latlng = new google.maps.LatLng(51.474634, -0.195791);
var mapOptions1 = {
zoom: 14,
center: latlng
}
var geocoder = new google.maps.Geocoder();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions1);
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, 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,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
}
where markers variable is bringing proper data, my test data is array of 5 elements
The Game Larder, 24 The Parade, Claygate, Surrey,KT10 0NU
24 The Parade, Claygate, Esher, Surrey KT10 0NU
Card Collection, 14 The Parade, Claygate, ESHER, KT10 0NU
16A The Parade, Claygate, ESHER, KT10 0NU
and same is coming into array markers however it is plotting only two markers. What could be wrong here
Solution
I was entering locations which are very close to each other e.g 1 and 2 point which gives same latlong hence mark as one place. I found latlong here. Thanks for answers btw :)
In page.aspx. insert tag <div id="map-canvas" ></div>
view source page.aspx and insert script into it>
var lis_marker = new Array();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
lis_marker[i] = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
there are difference with your code:
1: var lis_marker = new Array();
2: lis_marker[i] = new google.maps.Marker({...});

get place within the given lat and long in ajax

i am in a trouble to find the places within the lat, long and radius using ajax or javascript , i used a ajax code to find this but getting error,
my code is :
$.ajax({ url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?',
data: {
location:'-33.8670522,151.1957362',
radius:500,
sensor:false,
key:'AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I'},
dataType: "json",
type: "GET", //or POST if you want => update your php in that case
success: function( data ) {
for(var i in data.results){
alert(data.results[i]);
}
},
error: function (request, status, error) {
alert("error");
//handle errors
}
});
it gets the result error, please help me to find this
Thanks
try the following code to get places from near by locations
function initialize(arg)
{
directionsDisplay = new google.maps.DirectionsRenderer();
mapmarker="img/pois/"+arg+".png";
geocoder = new google.maps.Geocoder();
var location = new google.maps.LatLng(11.21989,78.16811099999995);
map = new google.maps.Map(document.getElementById('googleMap'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: location,
zoom: 15
});
directionsDisplay.setMap(map);
var request = {
location: location,
radius: '5000',
types: [arg]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
//google.maps.event.addDomListener(window, 'load', initialize);
function callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
var place = results[i];
createMarker(results[i]);
}
}
}

Categories