Google map on ajax success - javascript

I have the following Ajax request on a select drop down change which simply gets the records from the controller, Loop through each one and get the latitude | longitude and pushes it to an array.
Then in the same ajax success i pass that lat and lng array to google map.
But the map doesn't shows up..
$(document).ready(function() {
$('.selectCity').change(function() {
var city = $(this).val();
$.ajax({
type: 'GET',
url: '/riders/location/track',
data: {
'city': city
},
success: function(data) {
var lat = [];
var lng = [];
//Get Locations and push it to lat and lng
$.each(data, function(index, value) {
$.each(value, function(index1, value1) {
console.log(value1.rider_location.lat);
lat.push(value1.rider_location.lat);
lng.push(value1.rider_location.lng);
});
});
//Google Map
google.maps.event.addDomListener(window, 'load', init);
function init() {
var locations = [
['Rider', lat, lng]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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));
}
}
}
});
});
});
Plus please suggest best practice also.

Of course I can make my comment above as an answer.
You can also listen to the "google-maps-ready"-event in the script-url by using the callback-parameter (HTML):
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?libraries=geometry,places&callback=initialize">
</script>
JS:
// In this way you have to define a function called initialize which should be defined globally otherwise it can not be found by the google-library.
// unfortunately this map-variable is defined globally here but you can also wrap the whole code below by using an IIFE.
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
// you might set a center here or wait untill you have got some markers fetched via ajax, you can then use the first/last or some other marker respecetive it's position(lat,long) to set as "starting point"
//center: {lat: LAT, lng: LONG }
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// Although I have no access to your website to test this code below, it might be done in this way:
$(document).ready(function () {
$('.selectCity').change(function () {
var city = $(this).val();
$.ajax({
type: 'GET',
url: '/riders/location/track',
data: {
'city': city
},
success: function (data) {
var positions = [];
//Get Locations and push it to lat and lng
// you can also use just one array to insert all locations and "labels" into
$.each(data, function (index, value) {
$.each(value, function (index1, value1) {
console.log(value1.rider_location.lat);
positions.push({
lat: value1.rider_location.lat,
lng: value1.rider_location.lng,
content: 'Rider' // do you get some text with each location?
});
});
});
// set "starting point" afterwards
map.setCenter({
lat: positions[0].lat,
lng: positions[0].lng
});
var infowindow = new google.maps.InfoWindow();
var marker,
i;
for (i = 0; i < positions.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat, positions[i].lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(positions[i].content);
infowindow.open(map, marker);
}
}) (marker, i));
}
}
});
});
});
Hope it helps!

Related

How to delete markers from my own google maps

I am trying to delete markers from my own google maps, but my code didnt work and I don't know why. Would you like to help me? Thanks!
Data in function removeMarkers() - markers.length, is stil empty, if I try to debug by console.log(markers.length);
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(49.8037633, 15.4749126)
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.addDomListener(document.getElementById('add-markers'), 'click', addMarkers);
google.maps.event.addDomListener(document.getElementById('remove-markers'), 'click', removeMarkers);
}
function addMarkers() {
var markerCluster;
$.ajax({
type: 'GET',
url: 'get-places.php',
dataType: 'json',
success: function(data) {
var markers = [];
$.each(data, function(index, element) {
var latLng = new google.maps.LatLng(element.lat, element.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
// icon: icon,
title: element.title
});
markers.push(marker);
var details = element.name;
bindInfoWindow(marker, map, infowindow, details);
});
markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
});
}
function removeMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function bindInfoWindow(marker, map, infowindow, strDescription) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(strDescription);
infowindow.open(map, marker);
});
}
initialize();
Function addMarkers() works well, but removeMarkers() not.
You have a global variable as var markers = []; but you do not populate this when you get AJAX response back. What you do in function addMarkers() is populate the variable markers inside this function which is local to this function.
You will need to remove var markers = []; from function addMarkers() and instead use the global variable to populate markers from your AJAX response. Then you will be able to remove markers in removeMarkers function.
var markers = []; // this is global scope
function addMarkers(){
var markers = []; // remove this declaration in this function as it creates local scope
}
function removeMarkers(){
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = []; // do not forget to set this empty
}
You should remove the re-declaration of markers array. Your removeMarkers function does not know about the markers array you're populating inside your success callback.
var markers = [];
...
success: function(data) {
var markers = []; // <- remove that redeclaration

Need To Remove Previous Marker From Map Without refreshing the google map

I need to remove the previously added marker ,without refreshing the screen ,tried many codes for past 2 days but not able to do. This question might sound like a duplicate ,yes it is but in my case I am not able to fix the bug ,any suggestions and helps would be very useful. I have attached my code below.Thanks In advance.
P.S : I am new to google maps (project built on C# code,javascript, asp.net mvc, ms sql db)
var map = new GMaps({
el: '#map',
lat: 11.0168,
lng: 76.9558
});
geolocate();
function geolocate() {
$.ajax({
url: '#Url.Action("loadmap", "LiveTracking")',
type: "Get",
dataType: 'json',
success: function (results) {
debugger;
var result = JSON.parse(results);
var lat = parseFloat(result[0].Latitude)
var lng = parseFloat(result[0].Longitude)
var VehicleId = result[0].VehicleID;
var Speed = result[0].Speed;
var abc = ("Vehicle:" + VehicleId + " , " + "Speed:" + Speed )
map.addMarker({
lat: lat,
lng: lng,
icon: {
url: '/Content/Images/zaz.png',
scaledSize: new google.maps.Size(65, 65),
},
title: 'vehicle',
infoWindow: {
content: abc
},
});
// }
}
})
}
Most commonly suggested method was to add an marker[] and push in it and call the delete function ,which I tried but can't able to achieve it.
Hope anyone can help me out,thanks in advance
Have you looked at this documentation?
https://developers.google.com/maps/documentation/javascript/examples/marker-remove
It has clearMarkers() before setting the empty array.
function deleteMarkers() {
clearMarkers();
markers = [];
}
function clearMarkers() {
setMapOnAll(null);
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
<body onload="googleMap()">
<div id="map_canvas" style="height: 300px; width: 300px"></div>
<a onclick="removeMarker()">Remove marker</a>
<script type="text/javascript">
var map, myLatLng, marker;
function googleMap() {
var mapOptions = {
center: new google.maps.LatLng(52.645813,-0.382000),
zoom: 15,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myLatLng = new google.maps.LatLng(52.645945,-0.382837);
marker = new google.maps.Marker({ position: myLatLng, map: map });
};
function removeMarker() {
marker.setMap(null);
};
</script>
</body>

Google Maps JS API + JSON - Multiple markers not showing up

So, what I need is very simple, I need to put markers in a map, I get the data from a JSON I built using PHP. I looked up all other questions(really) about Google Maps markers not showing up, and none of them worked for me. I can't find the flaw in my code.
The JSON is like this (but 58 items long), 'id' is unimportant:
[
{
"id": "2",
"lat": "-49.217290",
"lon": "-16.416160",
"tit": "Heinz",
"desc": "18 Machines"
},
{
"id": "3",
"lat": "-49.235455",
"lon": "-16.676926",
"tit": "Warehouse",
"desc": "10 Machines"
}
]
I'm new here, sorry if I do something wrong. My code is bellow:
<div id="map" class="height-400"></div>
<script>
var map;
var myLatLon = {lat: -16.398293, lng: -48.965098};
var markers = [];
$.ajax({
dataType:'json',
url: "contents/map_data.php",
success: function(data){
markers = data;
}
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLon,
zoom: 4,
//disableDefaultUI: true,
});
var i= 0;
$.each(markers, function(i, item) {
if(typeof item == 'object') {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(item.lat),parseFloat(item.lon)),
map: map,
title: item.titulo,
label: item.desc
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(item.desc);
infowindow.open(map, marker);
}
})(marker, i));
i=i+1;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initMap" async defer></script>
Markers variable is an empty array, cause the AJAX request has not returned yet. You should either move your code inside success callback or invoke it from success callback.
Try something like:
<div id="map" class="height-400"></div>
<script>
var map;
var myLatLon = {lat: -16.398293, lng: -48.965098};
var markers = [];
$.ajax({
dataType:'json',
url: "contents/map_data.php",
success: function(data){
markers = data;
initMap();
}
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLon,
zoom: 4,
//disableDefaultUI: true,
});
var i= 0;
$.each(markers, function(i, item) {
if(typeof item == 'object') {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(item.lat),parseFloat(item.lon)),
map: map,
title: item.titulo,
label: item.desc
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(item.desc);
infowindow.open(map, marker);
}
})(marker, i));
i=i+1;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initMap" async defer></script>

How to show geolocated tweets on a map

I have been playing around with the twitter API getting random tweets or even geo tagged tweets and also with the google maps API. However I want to combine this two and try and show geo tagged tweets on a google map. Here is my code for getting the geo tagged Tweets which work fine.
var geo = (geo.coordinates[0], geo.coordinates[1])
//var geo = (34.052234, -118.243685)
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
for(var index in data.statuses){
var tweet = data.statuses[index];
console.log(tweet.text);
console.log(tweet.geo.coordinates)
}
});
On a different file, I generated a map based on Longitude and Latitude, and I had the understanding that once I had retrieved the coordinates for the tweets, I could represent the tweets on a Google Map in the same way. However, my code is not working. My question is, how would I combine both pieces of code to generate a map which is marked with geo located Tweets?
function initialize() {
var myLatlng = new google.maps.LatLng(geo.coordinates[0], geo.coordinates[1]);
var mapOptions = {
center: myLatlng
zoom: 10,
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Tweet});
var infowindow = new google.maps.InfoWindow({
content: 'Geo tagged Tweet',
maxWidth:200 });
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker); });
}
google.maps.event.addDomListener(window, 'load', initialize);
I would do something like this (untested - I'm just writing down some thoughts).
1) You should strip down init so that it just contains the map set up. Ensure map is declared outside of the function, and include a call to the function that fetches your data using the lat/lng data.
var map;
function initialize() {
var lat = geo.coordinates[0];
var lng = geo.coordinates[1]
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = { center: myLatlng, zoom: 10 }
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
getData(lat, lng, processData);
}
2) You wrap your data fetching code in a new function declaration, which accepts lat/lng data, and a callback.
function getData(lat, lng, callback) {
client.get('search/tweets', { q:string.teamname, geocode: geo, count: 5},
function searchTweets(err, data, response) {
callback(data.statuses);
}
)
};
3) Process the tweet information. For each tweet create a marker (add the marker to an array of markers) and update the map
function processData(data) {
var markers = [];
for (var i = 0, l = data.length; i < l; i++) {
var marker = new google.maps.Marker({
id: i,
position: myLatlng(data[i].geo.coordinates[0], data[i].geo.coordinates[1),
map: map,
title: "Tweet"
});
markers.push(marker);
var infowindow = new google.maps.InfoWindow({
content: data[i].text,
maxWidth: 200
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}

howto: dynamically update markers from JSON on google maps

I am trying to update the location of a marker with out refreshing the whole page. I have tried to use setTimeout(function() however I am having no luck..
here is my code I have so far..
thanks in advance
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "getjson.php",
'dataType': "json",
'success': function (data) {
json = data; } });
return json;})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
here is my JSON output.
[{"lat":35.6606376,"lng":-80.5048653,"content":"bca"}, {"lat":42.6799504,"lng":-36.4949205,"content":"abc"}]
I would suggest using setInterval rather than setTimeout.
Here is some code that simulates an update via JSON in a fiddle, using your provided JSON with the required "description" member added for each marker:
var map = null;
var gmarkers = [];
var intervalNumber = 0;
setInterval(function () {
new Request.JSON({
url: '/echo/json/',
data: {
json: JSON.encode([{
"lat": 35.6606376 + (0.01 * intervalNumber),
"lng": -80.5048653 + (0.1 * intervalNumber),
"content": "bca",
"description":"first marker"
}, {
"lat": 42.6799504 + (0.01 * intervalNumber),
"lng": -36.4949205 - (0.1 * intervalNumber),
"content": "abc",
"description": "second marker"
}]),
delay: 3
},
onSuccess: function (response) {
update_map(response);
intervalNumber++;
}
}).send();
}, 5000);
update_map = function (data) {
var bounds = new google.maps.LatLngBounds();
// delete all existing markers first
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
// add new markers from the JSON data
for (var i = 0, length = data.length; i < length; i++) {
latLng = new google.maps.LatLng(data[i].lat, data[i].lng);
bounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data[i].title
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
})(marker, data[i]);
gmarkers.push(marker);
}
// zoom the map to show all the markers, may not be desirable.
map.fitBounds(bounds);
};
function initialize() {
// initialize the map on page load.
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
// add the markers to the map if they have been loaded already.
if (gmarkers.length > 0) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(map);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
https://developers.google.com/maps/documentation/javascript/reference
markerObject.setPosition(latlng:LatLng|LatLngLiteral)
I don't think you need to redraw the map, but in case you do:
google.maps.event.trigger(mapObject, 'resize');

Categories

Resources