Api and Ajax loading Google Maps Markers - javascript

I've tried to load Google Maps with marker from server using Ajax and Api.
I've tried everything but I don't know where is problem.
Map is loaded but markers are not. I also enclose picture from Postman of my Api response.
PLEASE HELP ME. I will be so glad to you.
Here is the code:
$.ajax({
type: "GET",
url: 'http://localhost:8000/api/bicykel/',
dataType: "json",
success: function (data) {
$.each(data, function (marker, data) {
var latLng = new google.maps.LatLng(data.bicykels.lat, data.bicykels.lng);
bounds.extend(latLng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent("<div class='pt-5 bg-dark p-4' style='width:300px';>"+"<h3>"+data.bicykels.name+"</h3>" + " " + data.bicykels.name+"</div>");
infoWindow.open(map, marker);
});
});
},
error: function (data) {
console.log('Please refresh the page and try again');
}
});
Here is the code of Api:
def customer_get_bicykel(request):
uzivatel = request.user.id
bicykels = BicykelSerializer(
Bicykel.objects.filter(),
many = True,
context = {"request": request}
).data
return JsonResponse({"bicykels": bicykels})
And also I enclose screen of api response:
Api Response
THANK YOU FOR EVRY HELP!

You're missing out to add the marker to the map. Quoting the google maps JS docs:
// To add the marker to the map, call setMap();
marker.setMap(map);

Related

How can I keep showing a Js var in HTML after route changes?

I'm bad with Javascript and would like your help!
Hi, I'm building a Rails application and would like to add some features related to geoloction. For that I get the current location of the user with JS and then print it with HTML.
As you guys will see, my code runs every time the page loads, but when my routes change, for example: /about, /settings, /events, it simply disappear and I have to load the page again to print the HTML element.
/* CURRENT LOCATION */
function geolocationSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latlng = {lat: latitude, lng: longitude};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]){
var user_address = results[0].formatted_address;
document.getElementById("current_location").innerHTML = user_address;
}else {
console.log('No results found for these coords.');
}
}else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function geolocationError() {
console.log("please enable location for this feature to work!");
}
$(document).ready(function() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
How can I have the current location printed on this element in all my application routes?
I wouldn't like to request this information every time.
Maybe a cookie? I don't know...
or request just once every some time
What do you guys recommend? Please help me :)
You can use localStorage for this purpose: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
localStorage allows you to save data between browser sessions and windows.
An example usage might be:
...
// Somewhere in geocode request callback
localStorage.setItem('user_address', results[0].formatted_address)
...
// Somewhere in your render code
document.getElementById("current_location").innerHTML =
localStorage.getItem('user_address')
...

"dragend" event listener only firing on load (once) Google Maps

I am sure i have structured this wrong, but the event listener for "dragend" is not firing. When I change the event to bounds_changed or center_changed then it only fires on the initial page load. Is there anything that stands out as to why it is behaving like this?
I basically just want to call my searchStores() function everytime the map is repositioned so it becomes reactive to the user.
var map;
$(document).ready(function () {
var latlng = new google.maps.LatLng(36.2994410, -82.3409052);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create the new map with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$("#btnSearch").click(function(){
//Convert Address Into LatLng and Retrieve Address Near by
convertAddressToLatLng($("#txtAddress").val());
});
//send user to print/save view on click
$("#saveAs").click(function() {
window.location.href = "https://54.90.210.118/test.html?address=" + $("#txtAddress").val() + '&radius=' + $("#radiusO").val();
});
//WHAT IS GOING ON WITH THIS GUY???
google.maps.event.addListener(map, "dragend", function() {
alert('map dragged');
});
});
$(document).one('ready', function(){
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
latlngloc = new google.maps.LatLng(pos.lat, pos.lng);
map.setCenter(pos);
$("#divStores").html('');
searchStores(latlngloc);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
});
Thanks for the help! I found the issue was on another function that ended up clearing the map object and then recreating it. Therefore removing the listener.
Sorry for the confusion, and thanks for pointing out that it worked on Jfiddle. I thought it was something to do with how I was calling it.
I am really new to Javascript and having to teach myself bit by bit. Thanks for all the help! =)

navigator.geolocation.getCurrentPosition won't reset with new location on Android

I'm trying to build a tracker that only requires a browser window be open, on mobile devices. All of the code seems to work, other than navigator.gelocation.getCurrentPosition. As you can see, I'm using a timer to cycle my code every few seconds. I was expecting the code within the time to output real-time location information, but instead, it seems to resort to using the last known location - or if there isn't one, it will find the location and then keep using the same one.
I'm not sure if this is an issue with Android or my code, but it seemed to work well on an iPhone - but it wasn't me who tested it, so I can't really be sure.
Thanks in advance!
var lati = " ";
var longi = " ";
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 15
});
var timerID = setInterval(function() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
var infoWindow = new google.maps.InfoWindow({map: map});
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
lati = (position.coords.latitude);
longi = (position.coords.longitude);
console.log(lati, "Lol");
infoWindow.setPosition(pos);
infoWindow.setContent('lati');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
//in a loop (setInterval) get coords and apply them to database
{
$.ajax({ url: 'php_test.php',
data: {'Lati': lati, 'Longi': longi},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
}
});
}
}, 2 * 1000);
}
I'm facing the same issue but I realize debugging that getCurrentPosition is deprecated on insecure origins.
https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
Maybe you can achieve something like How do I get the current GPS location programmatically in Android?

Google Maps reverse geocoding address appears after second click?

Currently if I click on a marker, error in console shows "address undefined" but if i click it again the address shows up, why is this happening?
What my listener looks like:
map.data.addListener('click', function(event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
function getReverseGeocodingData() {
var latlng = new google.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
address = (results[0].formatted_address);
}
});
}
getReverseGeocodingData(lat, lng);
infoWindow.setContent("Address: " + address + "<br>Vehicle: " + event.feature.getProperty('deviceID')+"<br> Speed: "+event.feature.getProperty('speedKPH'));
infoWindow.setPosition(event.latLng);
infoWindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infoWindow.open(map);
});
thank you for your time and help in advance.
geocoder.geocode works asynchronously, which means the callback will be invoked later™. You are calling this method from the synchronous method getReverseGeocodingData, and then proceed to use the address data immediately afterwards.
This can't work.
Asynchronous communication can be visualized with traditional paper mail. Imagine you send a letter to Google to get the address at x,y. After you put the letter in the postbox, you don't have the result just yet, so you can't print that sign with the address on it yet. But you can do other stuff, like repainting your house (yeah, the metaphor is stretched). You will have to be patient to wait for the answer via mail.
A few days later the mailman rings, and delivers you the answer from Mountain View. It says: "x,y is at Hauptstraße 22". Now you can start printing that sign (and this is where the metaphor ends) to the status bar of your browser.
On the other hand, you can visualize synchronous communication with phone calls. You get the answer immediately, and you can't do anything else during the call. After you hung up, you got the answer.
In JavaScript, we are pretty much stuck with the asynchronous model. If this is good or bad is not for today to decide ;-)
So thanks thriqon i understood the problem,
and have come up with this solution which i'm not sure how correct it is, but it does what i need it to do. It calls for the address once they hover over the point in the background without popping up the infowindow and when they click, tada, the address is shown in the infowindow! hope this helps some people! messsssy code
map.data.addListener('mouseover', function(event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
address = (results[0].formatted_address);
return address;
}
});
}
getReverseGeocodingData(lat, lng);
map.data.addListener('click', function(event) {
infoWindow.setContent("Address: " + address + "<br>Vehicle: " + event.feature.getProperty('deviceID') +"<br> Speed: "+event.feature.getProperty('speedKPH')+"<br> Heading:"+event.feature.getProperty('heading'));
infoWindow.setPosition(event.latLng);
infoWindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infoWindow.open(map);
});
});

Google Map V3 infowindows

I’m developing a website that incorporates a Google map v3 and I would like to know how to programmatically close the infowindows that can be opened when the user clicks on the icons that are loaded with the map. I don’t mean the infowindows opened when the markers the site places on the map are clicked on.
Is this possible?
Thanks in advance
var marker = new google.maps.Marker({
map: $scope.map,
icon: image
});
var infowindow = new google.maps.InfoWindow({
content: 'some text'
});
marker.addListener('mousedown', function() {
infowindow.open($scope.map, marker);
if (!marker.open) {
infowindow.open($scope.map, marker);
marker.open = true;
setTimeout(function() {
infowindow.close();
marker.open = false;
}, 2000);
} else {
infowindow.close();
marker.open = false;
}
});
In ur case u just have to replace marker with icon , icon or whatever must have a mousedown or click listener.
And marker.open & close is just a variable

Categories