for each only running once - javascript

First let me explain. I have several addresses on the page that I put into an array. I then want to go over that array and replace each address with its longitude and latitude.
The problem is my attempt only runs one time.
$(function () {
var addr = 0;
var shops = [];
var addressPoint;
var latlng = new google.maps.LatLng(38, -97);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
window.onload = function () {
var options = [];
$('.address').each(function () {
if (!$(this).is(":empty")) {
options.push($(this).text());
txt = $(this).text();
} else {}
});
alert(options);
$.each(options, function () {
var addr = ("'" + this + "'");
searchAddr(addr);
});
function searchAddr(addr) {
$('#map_canvas').gmap({
'callback': function () {
var self = this;
alert(addr);
self.search({
'address': addr
}, function (results, status) {
if (status === 'OK') {
addressPoint = results[0].geometry.location;
alert(addressPoint);
options = $.map(options, function () {
return results[0].geometry.location;
});
self.get('map').panTo(results[0].geometry.location);
alert(options);
return false;
}
});
}
});
}
};
}(jQuery));

Did you use a network sniffer to confirm it is only firing once? Because it looks like you are replacing each value in the list with a single value in the $.map command. Perhaps if you put the address points in a different array it would help:
$(function () {
var addr = 0;
var shops = [];
var addressPoint;
var latlng = new google.maps.LatLng(38, -97);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var points = [];
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
window.onload = function () {
var options = [];
$('.address').each(function () {
if (!$(this).is(":empty")) {
options.push($(this).text());
txt = $(this).text();
} else {}
});
alert(options);
$.each(options, function () {
var addr = ("'" + this + "'");
searchAddr(addr);
});
function searchAddr(addr) {
$('#map_canvas').gmap({
'callback': function () {
var self = this;
alert(addr);
self.search({
'address': addr
}, function (results, status) {
if (status === 'OK') {
addressPoint = results[0].geometry.location;
alert(addressPoint);
points.push(addressPoint);
});
self.get('map').panTo(addressPoint);
alert(points);
return false;
}
});
}
});
}
};
}(jQuery));

Related

Laravel fetch longitude and latitude from database and display markers on Google Map

Hello guys I need help from you. I'm coding a web application using laravel framework. I've recorded logitudes, latitudes and other informations in the database. I want to fetch those informations and display their marker on google map. All examples I'm getting are for PHP scratch code. Is there anyone who can help me how to do it in laravel?
HERE IS THE DATABASE CODE
Schema::create('alertes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code');
$table->string('code_client');
$table->string('client_category');
$table->string('longitude');
$table->string('latitude');
$table->timestamps();
});
HERE IS MY BLADE FILE
<div id="map" style="width:100%;height:400px;"></div>
</div>
</div>
</div>
</div>
#endsection()
#section('custom-script')
<script type="text/javascript" src="{{asset('assets')}}/map/carte_alertes.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnyJJ2gorvX0rsuhBJLNUsfyioWSSep2Q&callback=init"></script>
<script>
</script>
#endsection
HERE IS MY SCRIPT.JS
<script>
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
// Beni
var center = new google.maps.LatLng(0.496422, 29.4751);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
makeRequest("{{route('alertes.index')}}", function (data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
// displayLocation method
function displayLocation(location) {
var content = '<div class="infoWindow"><strong>' + location.code_client + '</strong>'
+ '<br/>' + location.client_category + '</div>';
if (parseInt(location.latitude) == 0) {
geocoder.geocode({'client_category': location.client_category}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.latitude), parseFloat(location.longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.code_client
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
change callback=initMap not callback=init
src="https://maps.googleapis.com/maps/api/js?key=yourapikey&callback=init"></script>
try your data format this way
public function mapMarker(){
$locations = Alerte::all();
$map_markes = array ();
foreach ($locations as $key => $location) {
$map_markes[] = (object)array(
'code' => $location->code,
'code_client' => $location->code_client,
'client_category' => $location->client_category,
'longitude' => $location->longitude,
'latitude' => $location->latitude,
);
}
return response()->json($map_markes);
}
copy this code and re-place this code
content : `<div><h5>${Number(datas[index].latitude)}</h5><p><i class="icon address-icon"></i>${Number(datas[index].longitude)}</p></div>`
Still having the problem
HERE IS MY NE
function initMap(){
var mapElement = document.getElementById('map');
var url = '/map-marker';
async function markerscodes(){
var data = await axios(url);
var alerteData = data.data;
mapDisplay(alerteData);
}
markerscodes();
function mapDisplay(datas) {
//map otions
var options ={
center :{
lat:Number(datas[0].latitude), lng:Number(datas[0].longitude)
},
zoom : 10
}
//Create a map object and specify the DOM element for display
var map = new google.maps.Map(mapElement, options);
var markers = new Array();
for (let index = 0; index < datas.length; index++){
markers.push({
coords: {lat: Number(datas[index].latitude), lng:Number(datas[index].longitude)},
content : '<div><h5>${datas[index].code_du_suspect}</h5><p><i class="icon address-icon"></i>${datas[index].etat_du_suspect}</p></div>'
})
}
//looping through marker
for (var i = 0; i < markers.length; i++){
//une fontion a creer si dessous
addMarker(markers[i]);
}
function addMarker(props){
var marker = new gooogle.maps.Marker({
position : props.coords,
map: map
});
if(props.iconImage){
marker.setIcon(props.iconImage);
}
if(props.content){
var infoWindow = new google.maps.infoWindow({
content : props.content
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
}
}
}

javascript directions with google maps

how can i change the start = $("#from").val();, value option, to users current position? It's more comfortable without typing the start adress.
Any help?
<script type="text/javascript">
$(document).on("pageinit", "#map_page", function() {
initialize();
});
$(document).on('click', '#submit', function(e) {
e.preventDefault();
calculateRoute();
});
var directionDisplay,
directionsService = new google.maps.DirectionsService(),
map;
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
var mapCenter = new google.maps.LatLng(51.507009, -0.170720);
var myOptions = {
zoom:16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions"));
}
function calculateRoute()
{
var selectedMode = $("#mode").val(),
start = $("#from").val();,
end = new google.maps.LatLng(51.507009, -0.170720);
//start = $("#from").val();
if(start == '' || end == '')
{
// cannot calculate route
$("#results").hide();
return;
}
else
{
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
$("#results").show();
/*
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
alert(myRoute.steps[i].instructions);
}
*/
}
else {
$("#results").hide();
}
});
}
}
</script>
The solution is to use https and not http for getCurrentPosition() and watchPosition()

Callback js Google is empty

Im have js function, she calc latitude and longitude from zip code:
function GetLocation(adr, callback) {
var address = adr;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
// console.log([latitude, longitude])
callback([latitude, longitude]);
} else {
return "Request failed.";
}
});
}
When I call function in origin:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p) {
var myRouter = {
map_: null,
directionsHelper_: null,
calcRoute: function() {
var waypts = [];
for (var i in this.stores) {
waypts.push({
location: this.stores[i].location,
stopover:true
});
}
var request = {
origin: new google.maps.LatLng(
GetLocation(adress1, function(callback) {
console.log(callback[0]);
}),
GetLocation(adress1, function(callback) {
console.log(callback[1]);
})
),
Callback return is empty, if call before if(navigator.geolocation) that ok, how I can fix it?

Google map marker with angularjs for large data

I am building an widget where user can upload an excel file and the places are get marked in the google map.
The following code works, but issue comes when i am reading an large excel file with 10k amount of data, the browser gets stuck. I am using a for loop and adding some timeout to get the data from the google api.
I pass the city name and get the latitude and longitude and mark it on the map.
Is there a better way i can implement?
Here is the code:
function googleMapsInit(widId, $scope, $http, $rootScope, $mdDialog) {
$scope.finish = function() {
var objIndex = getRootObjectById(widId, $rootScope.dashboard.widgets);
$mdDialog.hide();
document.getElementById('map').innerHTML = "";
//excel data
var array = JSON.parse($rootScope.json_string);
$scope.locationData = [];
//dividing it to chunks
var k,j,temparray,chunk = 8;
for (k=0,j=array.length; k<j; k+=chunk) {
temparray = array.slice(k,k+chunk);
var i;
//getting the longitude and latitude from the google geo api
for(i=0;i < temparray.length ; i++){
Geocode(temparray[i].PLACE_OF_ACCIDENT);
}
}
//sometimes data gets delayed
setTimeout(function(){ googleMap(); }, 5000);
};
function Geocode(address) {
var obj = {};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
obj = {
lat : results[0].geometry.location.G,
lng : results[0].geometry.location.K
};
setTimeout(function(){ $scope.locationData.push(obj); }, 100);
}
else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else if (status === google.maps.GeocoderStatus.ZERO_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else {
}
});
}
function googleMap() {
var dataStore = $scope.locationData;
var array = JSON.parse($rootScope.json_string);
var map = new google.maps.Map(document.getElementById('map'),{
center: {lat: 7.85, lng: 80.65},
zoom: 6 });
var pinImageGreen = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/green-dot.png");
var pinImageBlue = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
var marker = [];
var k;
for(k=0; k < array.length; k++){
marker[k] = new google.maps.Marker({
position: {lat: $scope.locationData[k].lat, lng: $scope.locationData[k].lng},
map: map,
title: array[k].PLACE_OF_ACCIDENT,
icon: pinImageGreen,
VEHICLE_TYPE: array[k].VEHICLE_TYPE,
VEHICLE_USAGE: array[k].VEHICLE_USAGE,
VEHICLE_CLASS: array[k].VEHICLE_CLASS
});
marker[k].addListener('click', function(data) {
var j;
for(j=0;j<array.length;j++){
if(($scope.locationData[j].lat == data.latLng.G) && ($scope.locationData[j].lng == data.latLng.K )){
document.getElementById("details").innerHTML =
array[j].PLACE_OF_ACCIDENT + "</br>" +
array[j].VEHICLE_TYPE + "</br>" +
array[j].VEHICLE_USAGE + "</br>" +
array[j].VEHICLE_CLASS + "</br>" ;
}
}
});
}
}
$scope.cancel = function() {
$mdDialog.hide();
};
}
One way to slightly improve performance is this: Instead of adding markers to the map one at a time, just create the markers array separately and then add them all at once to the map. Here is a sample code:
var markersData = [];
for (var i = 0; i < myArray.length; i++) {
var item = scope.myArray[i];
if (item.lat != undefined && item.lon != undefined) {
var icon = 'icon.png';
markersData.push({
lat: item.lat,
lng: item.lon,
title: 'xyz'
});
}
}
map.addMarkers(markersData);
By the way I have used "gmaps.js" for this which simplifies coding google maps, but you don't necessarily need it. The general idea is to avoid adding markers to the map inside the loop, one by one.

How can I make both external JavaScript files work in my html file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The first JavaScript code works fine by itself, but when I add the other one it doesn't. I dont understand why.
When I remove the first JavaScript code the other code works fine too, but when I put them together the only js code that works is the first one. I need both of them to work but I can't figure it out.
First js code
var map;
function initialize() {
var mapOptions = {
zoom: 6
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Location.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
Second js code
var map, places, iw;
var markers = [];
var searchTimeout;
var centerMarker;
var autocomplete;
var hostnameRegexp = new RegExp('^https?://.+?/');
function initialize() {
var myLatlng = new google.maps;
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
document.getElementById('keyword').onkeyup = function(e) {
if (!e) var e = window.event;
if (e.keyCode != 13) return;
document.getElementById('keyword').blur();
search(document.getElementById('keyword').value);
}
var typeSelect = document.getElementById('type');
typeSelect.onchange = function() {
search();
};
var rankBySelect = document.getElementById('rankBy');
rankBySelect.onchange = function() {
search();
};
}
function tilesLoaded() {
search();
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', searchIfRankByProminence);
google.maps.event.addListener(map, 'dragend', search);
}
function searchIfRankByProminence() {
if (document.getElementById('rankBy').value == 'prominence') {
search();
}
}
function search() {
clearResults();
clearMarkers();
if (searchTimeout) {
window.clearTimeout(searchTimeout);
}
searchTimeout = window.setTimeout(reallyDoSearch, 500);
}
function reallyDoSearch() {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var rankBy = document.getElementById('rankBy').value;
var search = {};
if (keyword) {
search.keyword = keyword;
}
if (type != 'establishment') {
search.types = [type];
}
if (rankBy == 'distance' && (search.types || search.keyword)) {
search.rankBy = google.maps.places.RankBy.DISTANCE;
search.location = map.getCenter();
centerMarker = new google.maps.Marker({
position: search.location,
animation: google.maps.Animation.DROP,
map: map
});
} else {
search.bounds = map.getBounds();
}
places.search(search, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var icon = 'number_' + (i + 1) + '.png';
markers.push(new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP,
icon: icon
}));
google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
window.setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
if (centerMarker) {
centerMarker.setMap(null);
}
}
function dropMarker(i) {
return function() {
if (markers[i]) {
markers[i].setMap(map);
}
}
}
function addResult(result, i) {
var results = document.getElementById('results');
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 == 0 ? '#00FFFFFFF' : '#00FFFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = 'number_' + (i + 1) + '.png';
icon.setAttribute('class', 'placeIcon');
icon.setAttribute('className', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function getDetails(result, i) {
return function() {
places.getDetails({
reference: result.reference
}, showInfoWindow(i));
}
}
function showInfoWindow(i) {
return function(place, status) {
if (iw) {
iw.close();
iw = null;
}
if (status == google.maps.places.PlacesServiceStatus.OK) {
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[i]);
}
}
}
function getIWContent(place) {
var content = '';
content += '<table>';
content += '<tr class="iw_table_row">';
content += '<td style="text-align: left"><img class="hotelIcon" src="' + place.icon + '"/></td>';
content += '<td><b>' + place.name + '</b></td></tr>';
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Address:</td><td>' + place.vicinity + '</td></tr>';
if (place.formatted_phone_number) {
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Telephone:</td><td>' + place.formatted_phone_number + '</td></tr>';
}
if (place.rating) {
var ratingHtml = '';
for (var i = 0; i < 5; i++) {
if (place.rating < (i + 0.5)) {
ratingHtml += '✩';
} else {
ratingHtml += '✭';
}
}
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Rating:</td><td><span id="rating">' + ratingHtml + '</span></td></tr>';
}
if (place.website) {
var fullUrl = place.website;
var website = hostnameRegexp.exec(place.website);
if (website == null) {
website = 'http://' + place.website + '/';
fullUrl = website;
}
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Website:</td><td>' + website + '</td></tr>';
}
content += '</table>';
return content;
}
google.maps.event.addDomListener(window, 'load', initialize);
You're defining two functions named initialize(). Either change name on one of them, to set them apart, or merge the code in to one function. As it is written, the second initialize() will overwrite/override the first (in order of load).
You could also define "namespaces" for your different js files. This will enable you to have the same function names, but you'll have to call them using their namespace (outside of the scope of the namespace anyway):
var yourNamespace = {
initialize(): function() {
//...
}
};
var yourOtherNamespace = {
initialize(): function() {
//...
}
};
And to call these:
yourNamespace.initialize();
yourOtherNamespace.initialize();

Categories