Google maps api and geocoding api - issues adding markers - javascript

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);

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')}}"

Javascript & PHP show multiple trackers in Google Maps API

Currently, I'm developing a system that will bring all latitude and longitude from MySQLi DB, and will output every data on the page. Here is my PHP code (working without any problem):
header('Content-Type: text/html; charset=utf-8');
require('database.php');
$query = mysqli_query($mysqli, "SELECT * FROM `tracking`");
if (!$query)
{
die('Error: ' . mysqli_error($mysqli));
}
if(mysqli_num_rows($query) > 0){
$getList = array();
while ($row = mysqli_fetch_assoc($query)) {
$getList[] = $row;
}
for($i = 0, $l = count($getList); $i < $l; ++$i) {
echo $getList[$i]['lat'].",".$getList[$i]['lon']."\n";
}
}
e.g output: -71.99991299555996,-83.18116602 -22.809918399999997,-43.4211132 -22.8540416,-43.2488448
Now, I need bring all data and put into an array, and put whole latitude/longitude to markers in Google Maps. Check what I have tried:
var check = false;
function refreshAll() { // This function will be called every 60 seconds
var locations = [];
locations.length = 0;
$.ajax({
type: "GET",
url: "show.php",
success: function(x)
{
var items = x.split("\n");
for(i=0; i<items.length; i++){
var data = items[i];
if ((items[i]).length > 1) {
locations.push(items[i].trim());
}
}
if (check == false) { // this will avoid map refreshing, I need only markers update.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
check = true;
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
alert(locations[i]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
}
}
});}
The problem is: the markers is not being set, and have no errors in console. I'm working on this in the last two days and can't find any solution. Can you help me? Thank you.
As you can see here in the docs, the LatLng object is different than the one you are using.
So, replace:
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
With
locations[i] = locations[i].trim().split(',');
var latLng = {lat: Number(locations[i][0]), lng: Number(locations[i][1])};
marker = new google.maps.Marker({
position: latLng,
map: map
});
Check out, the map object is in your infoWindow variable, try to set there the positions.
This should be used inside the locations loop.
var pos = {
lat: latitude,
lng: longitude
};
infoWindow.setPosition(pos);

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>

display data in a loop using javascript

I'm trying to get the markers longitude and latitude and display them on the map but I'm not getting any result, my parser.php file is working and fetching the data from the database i just need to format it into javascript anyone ?
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: -25.363882, lng: 131.044922},
zoom: 14
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
$.getJSON('parser.php', function(items) {
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon);
})(items[i]);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
parser.php output
[{"0":"33.880561","lat":"33.880561","1":"35.542831","lon":"35.542831"},{"0":"-25.363882","lat":"131.044922","1":"35.513477","lon":"35.513477"}]
addMarker needs to take map as an argument.
function addMarker(map, lat, long) {
var latlong = google.maps.LatLng(lat, long);
return new google.maps.Marker({
position: latlong,
map: map
});
}
Then your loop should be:
for (var i = 0; i < items.length; i++) {
item = items[i];
addMarker(map, item.lat, item.lon);
}
You don't need to put the addMarker calls into a closure, because these aren't separate callbacks.

Google Maps - Creating multiple markers

I'm having a bit of trouble trying to loop out multiple markers onto a map using information stored in an array.
The code creates the map no problem, but it's not displaying the markers I'm trying to loop out...
As you can see from the code below, there are two functions that are creating markers. The first is simply using two values. This marker displays fine.
The second function however, is grabbing the data from an array (the array has been set up to "squish" the latitude and longitude data together, in that order, as Google Maps requires it to be) and does not display anything when run.
Any ideas? I'm stumped!
Thanks in advance!
Here's the code:
Initial "locations" array:
var locations = new Array();
for (var i = 0; i < data.length; i++)
{
var row = data[i];
var longitude = row[0];
var latitude = row[1];
locations[i] = latitude + longitude;
}
callMap(locations, locationFilename, userLatitude, userLongitude);
Google Maps Functions
function callMap(locations, locationFilename, userLatitude, userLongitude) {
var mapOptions = {
zoom:16,
center: new google.maps.LatLng(userLatitude, userLongitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('mapView'),mapOptions);
setMarkers(map, locations, locationFilename);
currentPosition(map, userLatitude, userLongitude);
}
function currentPosition(map, userLatitude, userLongitude)
{
var userLatLng = new google.maps.LatLng(userLatitude, userLongitude);
var marker = new google.maps.Marker({
position: userLatLng,
map: map
});
}
function setMarkers(map, locations, locationFilename) {
for (var i = 0; i < locations.length; i++) {
var markerLatLng = new google.maps.LatLng(locations[i]);
var marker = new google.maps.Marker({
position: markerLatLng,
map: map
});
}
}
A google.maps.LatLng takes two numbers for arguments.
This is not correct:
var markerLatLng = new google.maps.LatLng(locations[i]);
This should work:
for (var i = 0; i < data.length; i++)
{
var row = data[i];
var longitude = row[0];
var latitude = row[1];
locations[i] = new google.maps.LatLng(latitude,longitude);
}
Then
function setMarkers(map, locations, locationFilename) {
for (var i = 0; i < locations.length; i++) {
var markerLatLng = locations[i];
var marker = new google.maps.Marker({
position: markerLatLng,
map: map
});
}
}
}
You're just adding strings together, it needs to be an array:
for (var i = 0; i < data.length; i++) {
var row = data[i];
var longitude = row[0];
var latitude = row[1];
locations[i] = [latitude, longitude];
}
var markerLatLng = new google.maps.LatLng(locations[i].join(','));

Categories