How to run success function with JQuery getJSON? - javascript

I want to push data to an array, but am unsure how to go about this due to AJAX's asychronisity.
I can't seem to find complete examples online of the way this is done with getJSON.
I've been following the documentation here with no luck/
I have tried:
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=" + addressval;
var latlng;
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
}).done(function() {
markerlocations.push(latlng);
})//END JSON
and:
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=" + addressval;
var latlng;
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
markerlocations.push(latlng);
});
and variations of this with no results.
Would anyone know the correct way of doing this and can point me in the right direction?

You need to push() to the array in the success handler which has access to the data returned from the request. You would also be better to add objects to the array instead of manually hacking around a JSON string. From there you can pass the array to whatever function you need to execute. Try this:
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat; // note 'lat' here, not 'lng'
var lng = data.results[0].geometry.location.lng;
markerlocations.push({ lat: lat, lng: lng });
doSomethingWithTheArray(markerlocations);
});
function doSomethingWithTheArray(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i].lat, arr[i].lng);
}
}

Try this. Use foreach to create your array. Then push/append the array as you want.
$.getJSON("url here", function(data) {
$.each(data, function(key, value){
// your custom code here
var latlng = 'code you want';
});
markerlocations.push(latlng);
});

You need to declare an empty array outside getJSON() function. Then it is accessible inside getJSON callback.
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
markerlocations.push({ lat: lat, lng: lng });
});
function(data)... is the callback function which gets executed once the response is obtained. You don't need another done() method in this case.
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=new york";
var latlng;
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
markerlocations.push(latlng);
// just for testing
for(var i = 0; i < markerlocations.length; i++){
alert(markerlocations[i].lat + '===' + markerlocations[i].lng);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Iteration in Javascript doesn't run [duplicate]

I scraped data from Json and containing arrays in queryLat/queryLng after that I create another function initMap also bind it to google script. But I having hard to time passing queryLat and queryLng into initMap. "queryLat is not defined" pops up. How I can pass those to initMap.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var newMarker = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
For multiple markers if you are defining arrays globally then you have to push your lat and long values in array and also need to update the marker variable to display diferent markers.. Hope it helps you to get the multiple markers.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat.push(data.results[0].geometry.location.lat);
queryLng.push(data.results[0].geometry.location.lng);
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var new_marker_str = "newMarker"+i;
new_marker_str = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
You Should define your variables queryLat and queryLng globally where your script starts.
<script type="text/javascript">
var queryLat;
var queryLng;
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 12,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
var marker = new
google.maps.Marker
({
position: {lat: queryLat, lng: queryLng},
map: map
});
}
The problem is in this code:
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
You have enclosed the string with apostrophes, but the string contains apostrophes too.
Use this instead:
url: "https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}"

Google maps api and geocoding api - issues adding markers

I will start by saying that I am relatively new to JS, so please forgive my ignorance if this is obvious.
I am trying to add markers to a google map. I have created an array coordList, then used the geocoding api to get the lag and long from the addresses and pushed them into coordList.
I am now trying to use the coordList array to plot markers on the map, however I cannot seem to get the values from the coordList array. When I run console.log(typeof coordList) - it tells me it's an object, but when i look at the array with console.log(coordList) it just looks like a normal array?
var coordList = [];
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLong(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
var coords = [];
coords.push(lat);
coords.push(lng);
//push coords into coordList
coordList.push(coords);
});
}
}
// Loop through the results array and place a marker for each
// set of coordinates.
function addMarkers(coordList) {
for (var i = 0; i < coordList.length; i++) {
var coords = coordList[i];
var latLng = new google.maps.LatLng(coords[0],coords[1]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
getLatLong(address);
addMarkers(coordList);
Your problem is that $.getJSON() is an asynchronous request and your code executes addMarkers() before than $.getJSON() finishes, so coordList is empty.
You can add the markers inside $.getJSON() callback. For example:
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLongAndAddMarkers(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var latLong = new google.maps.LatLng(data.results[0].geometry.location);
//add markers here
var marker = new google.maps.Marker({
position: latLong,
map: map
});
});
}
}
getLatLongAndAddMarkers(address);

Google Map Marker not working when from DB

I'm starting to learn Google Map. It's strange that when statically declared, markers are working and being displayed, but when they come from DB, they aren't being drawn on map.
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
I have the entire code here, maybe I am missing something? I even used console log and I successfully pass all data from ajax to markers variable.
I think I got this code somewhere here in SO and modified it to fit in for my DB calls for records. I hope you can help me out on this one. Thank you!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script type="text/javascript">
var map;
var global_markers = [];
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(15.058607, 120.660884);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.ajax({
type: 'GET',
url: 'control_panel/get_device_list_ajax',
success:
function (data) {
data = JSON.parse(data);
if (data['success']){
var device = data['device_list'];
device.forEach(function (dev) {
markers.push([dev['dev_geolat'], dev['dev_geolng'], dev['dev_name']]);
//console.log(markers);
});
addMarker();
} else {
}
}
});
}
function addMarker() {
console.log(markers);
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
</script>
EDIT
Here is the jsfiddle I used to work with this one http://jsfiddle.net/kjy112/ZLuTg/ (thank you to the one that lead me to this)
Could be related to the way you accessing to json rendered by ajax
markers.push([dev.dev_geolat, dev.dev_geolng, dev.dev_name]);
or the json content
I don't know how to close this question as I overlooked some problems on my DB but I'll be posting my answer if someone may come with the same problem (well, I am not sure about that hehe)
I get the same response from AJAX of the values in DB and I am not able to draw markers on MAP, I found that db->table->fields LAT LNG are referenced with a data type of DECIMAL (7,5) and changed it to FLOAT (10, 6) as to what is found in this GOOGLE MAP Tutorial - Using PHP/MySQL with Google Maps.
The issue at the field before was that higher values tend to be saved as 99.999999 instead of the actual value (e.g. 120.XXXXX) .

Show all geopoints of parse.com in google maps

I'm trying to take all the geopoints from a class in parse.com and show them as markers in a google map. (about only 1 geoipoin, lat lng, is working like a charm so here is the code)
function businessProfile(uid) {
Parse.initialize("APPID", "JSKEY");
var bprofile = Parse.Object.extend("magazia");
var query = new Parse.Query(bprofile);
query.notEqualTo("objectId", null);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) { var object = results[i];
var locationsBlock = {};
locationsBlock = JSON.parse(JSON.stringify(object));
var location = {};
location = JSON.parse(JSON.stringify(locationsBlock.latlon));
var lat = location.latitude;
var lon = location.longitude;
var magname = object.get('name');
setData(magname, lat, lon);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
So with the code above i get all the geopoints of 16 different rows and i push them into an array (i hope i do it properly), which array is declared outside of the function because i call it again on the map initialiazation function below.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 34.9, lng: 111.2}
});
setMarkers(map);
}
function setData(magname, lat, lon){
var arlat = [];
arlat.push(magname, lat, lon);
console.log(arlat);
}
function setMarkers(map) {
for (var i = 0; i < arlat.length; i++) {
var arlat = arlat[i];
var marker = new google.maps.Marker({
position: {lat: arlat[1], lng: arlat[2]},
map: map,
title: arlat[0]
});
}
}
So now i'm stuck on how to place each geopoint into the map with markers.
I know it has to do with the "for loop" but i'm stucked there. Now it shows only the first on the list marker, and i want to show them all.
UPDATE
So one update on my code i've managed to pass all the names and the lat lon that i get from my class in parse and now i put them in the function setData()
Now the question is, how can i pass the arlat array in the setMarkers() since the setMarkers function takes the map variable from the initMap() and i want it to take also the arlat array from the setData() function so i can print in the right section the lat lon and name? Here is a preview of the console.log(arlat)
Instead of pushing three variables:
arlat.push(magname, lat, lon);
You probably should push an object, like this:
arlat.push({lat: lat, lon: lon});
Then We just need to iterate over the pins (you could do it with a for loop, but a forEach might be simpler because you don't have to index into the array, just use a callback function that accepts the array element)...
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: iconBase + 'marker.png',
title: 'Hello World!'
});
arlat.forEach(function(positionObject) {
var pin = new google.maps.Marker({
position: {
lat: positionObject.lat,
lon: positionObject.lon
},
map: map,
//title: positionObject.title, //if title property is set above
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00ff00' //green pin, more available
});
});
Does that work for you? For more info about icons, checkout the google maps API (which you likely already have looked at)
UPDATE - based on your update, I noticed you are reassigning the value of arlat, which conflicts with the foreach iterations. I have changed it to use objects, and not overwrite the array object - see this plunkr or the code snippet below.
function initialize() {
var arlat = [];
setData('a', 34.0, 111.2);
setData('v', 30.1, 116.3);
initMap();
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 34.9,
lng: 111.2
}
});
setMarkers(map);
}
function setData(magname, lat, lon) {
//notice how we name the properties below: name, lat, lon - these are referenced down below in setMarkers()
arlat.push({
name: magname,
lat: lat,
lon: lon
});
}
function setMarkers(map) {
for (var i = 0; i < arlat.length; i++) {
var marker = new google.maps.Marker({
position: {
lat: arlat[i].lat,
lng: arlat[i].lon
},
map: map,
title: arlat[i].name
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 90%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<div id="map"></div>

Prohibit looping functions

Function onSuccess runs indefinitely, as constantly asks the coordinates from the GPS receiver. It contains a function createMap, to be performed only once. How is this achieved? Make a function outside the function also can not, because it is passed as a parameter value of a variable of the function.
watchID = navigator.geolocation.watchPosition(function(position) {onSuccess(position, arrMyLatLng);}, onError, options);
function onSuccess(position, arrMyLatLng)
{
var latitude , longitude ;
latitude = position.coords.latitude ;
longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);
createMap(myLatLng, arrMyLatLng);// This feature will run for an indefinite number of times. It is only necessary once.
map.panTo(myLatLng) ;
}
You can create a function with private state using a closure:
onSuccess = (function() {
var created = false;
return function (position, arrMyLatLng) {
var latitude , longitude ;
latitude = position.coords.latitude ;
longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);
if (!created) {
createMap(myLatLng, arrMyLatLng);
created = true;
}
map.panTo(myLatLng) ;
};
}());
Function that runs only once:
function runOnce() {
if (runOnce.done) {
return;
} else {
// do my code ...
runOnce.done = true;
}
}
Because function is object in JavaScript, you may set a property on it.
Assuming createMap returns a map
var map = null;
function onSuccess(position, arrMyLatLng) {
var latitude = position.coords.latitude ;
var longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);
map = map || createMap(myLatLng, arrMyLatLng);
map.panTo(myLatLng);
}
createMap will only run if map evaluates to "false" (i.e. is null), thus createMap only runs once.

Categories