my VueJS/Laravel application does not load in GoogleMaps properly as I would expect. I dont understand why the callback is not called. The function is available and it should load. can you help me? I do not find my mistake. I dont expect to see the map yet as I only have a consol.log in the init, but even this is not called. The error message when I open the full google URL is:
The Google Maps API server rejected your request. Invalid request.
Invalid 'callback' parameter.
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init async defer"></script>
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>INSPINIA - #yield('title') </title>
<link rel="stylesheet" href="{!! asset('css/vendor.css') !!}" />
<link rel="stylesheet" href="{!! asset('css/app.css') !!}" />
</head>
<body>
<!-- Wrapper-->
<div id="wrapper">
<!-- Navigation -->
#include('layouts.navigation')
<!-- Page wraper -->
<div id="page-wrapper" class="gray-bg">
<!-- Page wrapper -->
#include('layouts.topnavbar')
<!-- Main view -->
#yield('content')
<!-- Footer -->
#include('layouts.footer')
</div>
<!-- End page wrapper-->
</div>
<!-- End wrapper-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js"></script>
<script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>
<script src="{!! asset('js/main.js') !!}" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init async defer"></script>
#section('scripts')
#show
</body>
</html>
Main JS
const GISView = require('./components/GISView.vue');
window.Vue = Vue;
window.Event = new class {
constructor() {
this.Vue = new Vue();
}
fire(event, data = null) {
this.Vue.$emit(event, data);
}
listen(event, callback) {
this.Vue.$on(event, callback);
}
};
var App = window.App = new Vue({
el: '#app',
components: {
GISView: GISView
},
data: {},
methods: {
init: function() {
console.log("OK");
}
}
});
GIS VUE
<template>
<div id="map"></div>
</template>
<script>
import GoogleMaps from '../mixins/GoogleMaps.js';
export default {
mixins: [GoogleMaps],
data: {
test: 1
},
mounted() {
this.initMap();
},
methods: {
initMap: function() {
this.map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 83.298, lng: 35.555},
scollwheel: false,
zoom: 4
})
}
}
}
</script>
#map {height:300px;width:500px;}
Change
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init async defer"></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init" async defer ></script>
And please make sure your API key is not KEY ;)
The only change is moving the async and defer to outside of the API URL
Related
So I am very confused on how Chrome caches information, my problem is I cannot load in my leaflet map. When I run this code in IIS locally Chrome would cache the old site data and would not update anymore. Then I use ngrok and I clear cache and I have no more map.
At the moment my map is not even loading in locally anymore, I am sure this is very easy and I am missing something please someone explain this to me or point me to a resource to help me. Thanks for any help!
Javascript:
// Create map and get user location
$(document).ready(() => {
createMap()
});
// Map function
const createMap = async () => {
"use strict"
let map = L.map('mapid').setView([51.505, -0.09], 13);
const tileOptions = {
maxZoom: 5,
attribution: '© OpenStreetMap contributors'
}
let OpenStreetMap_Mapnik = await L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tileOptions).addTo(map);
}
// Update countries list
const getCountry = $.ajax("libs/php/getCountry.php")
getCountry
.done(result => {
if (result.status.name == "ok") {
result["data"].forEach(el => {
$('#countryList').append(new Option(el["name"], el["iso_a2"]));
});
}
})
.catch(err => {
console.log(err)
})
// DOM update
$("#search").click(() => {
console.log($("#countryList").find(":selected").text());
// // GET COUNTRY BORDERS
$.ajax({
url: "libs/php/getCountryBorders.php",
type: 'POST',
dataType: 'json',
data: {
country: $('select').val(),
},
success: function(result) {
// ADD COUNTRY BOUDS
console.log(result["data"]);
},
error: function(err) {console.log(err)}
})
})
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="source/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="source/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="source/favicon-16x16.png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>
<link rel="stylesheet" href="/libs/styles/style.css">
<title>Gazetter</title>
</head>
<body>
<div id="mapid"></div>
<!-- <div class="container-fluid">
<div class="row">
<div class="col-xs-4">
<select name="countryList" id="countryList" class="form-control">
<option value="">Select Country</option>
</select>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
</div>
<div class="col-xs-8">
<div id="mapid"></div>
</div>
</div>
</div> -->
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="/libs/javascript/script.js"></script>
</body>
</html>
Add a random string or number to end of all URLs that would load some data which doesn't refresh.
Something like this:
const getCountry = $.ajax("libs/php/getCountry.php?rand=" + Math.random())
You have disabled the html with the ids countryList and search and maybe then the js will throw errors in the lines $('#countryList').append(new Option(el["name"], el["iso_a2"]));, console.log($("#countryList").find(":selected").text());, country: $('select').val().
I recommand to test only the clean map without loading data.
Also I never saw await L.tileLayer(' I don't know if this is working correct but test it without await
I have Barba.js working on a website I am developing, I have debugged some other issues but I've noticed my jS isn't reinitialising between pages, which is not the intended behaviour. Please see my code below (I have removed my actual site content for the purposes of DRY):
index.html:
<head>
<!--- Default Page Values -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="favicon.png" />
<title>TEST.</title>
<!--- Load Local Styles -->
<link type="text/css" rel="stylesheet" href="fonts/fontsauce.css" />
<link rel="stylesheet" href="css/globals.css">
<link rel="stylesheet" href="css/header.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/videoModal.css">
<!--- End Load Local Styles -->
<!--- Load Local Scripts -->
<script src="js/lib/jQuery/jquery-3.5.1.min.js"></script>
<script src="js/lib/anime/anime.min.js"></script>
<script src="js/lib/parallax/parallax.min.js"></script>
<script src="js/lib/barba/2.9.7/barba.umd.js"></script>
<!--- End Load Local Scripts -->
<!--- Load External Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js" integrity="sha512-IQLehpLoVS4fNzl7IfH8Iowfm5+RiMGtHykgZJl9AWMgqx0AmJ6cRWcB+GaGVtIsnC4voMfm8f2vwtY+6oPjpQ==" crossorigin="anonymous"></script>
<!--- End Load External Scripts -->
</head>
<body id="barba-wrapper" data-barba="wrapper">
<main class="barba-container" data-barba="container" data-barba-namespace="home">
// all my website content //
</main>
<script src="js/introParams.js"></script>
<script src="js/parallaxParams.js"></script>
<script src="js/content.js"></script>
<script src="js/videoModal.js"></script>
<script src="js/pageTransitions.js"></script>
</body>
pageTransitions.js:
barba.init({
transitions: [{
name: 'diffuse-transition',
leave(data) {
return gsap.to(data.current.container, {
opacity: 0
});
},
beforeEnter: ({ next }) => {
window.scrollTo(0, 0);
},
enter(data) {
return gsap.from(data.next.container, {
opacity: 0
});
}
}]
});
The problem as I understand it, is that each time the content from a new page is loaded into the DOM, it's not re-initialising my other scripts. Any ideas how I can re-init my other scripts correctly?
Like you do for resetting scroll in the beforeEnter callback you also need to call your init methods from your scripts to reset them on a new page load. You also have afterEnter if you need to access the new page dom.
From the barba.js doc :
barba.init({
views: [{
namespace: 'home',
beforeEnter() {
// re-init/reset script default function on before page load
myScriptInit();
},
afterEnter() {
// refresh parallax on new page content
parallax.refresh();
}
}]
});
I suggest you take a look at the lifecycle of barba.js to help you.
In my case this helped:
barba.hooks.after(() => {
const bottomDOM = document.getElementsByTagName("body")[0]
const newScript = document.createElement("script")
const oldScript = document.querySelector(".main-script")
newScript.src = "js/main-dist.js"
newScript.className = "main-script"
oldScript.remove()
bottomDOM.appendChild(newScript)
})
I have a <script class="main-script"></script> at the end of the DOM, and use barba.hook to remove it and then add it again
I've gone through AMP-script documentation and I've been stuck for 1 day, trying to make this work.
I need to import JS remotely and use it in local. This is how I use it without AMP.
<!-- html -->
<span id="progressive_span">UPDATING</span>
<!-- js -->
<script src="https://tickers.ABC.com/hello.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function (event) {
var ticker = new Ticker({ info: 2 });
ticker.attachToTextBox('progressive_span');
ticker.SetCurrencySign('IDR ');
ticker.tick();
});
</script>
import amp-script component.
<!doctype html>
<html ⚡>
<head>
...
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
<meta name="amp-script-src" content="sha384-8T8pKdbkYmCLBlmEg0YkG9znnZfyf0AgBGSvAkuh5yeiOhD9K1PSaHOO3TjlrEkt"/>
<body>
Wrap the html element/s with the amp-script component:
<amp-script width="200" height="100" script="ticker">
<span id="progressive_span">UPDATING</span>
</amp-script>
The JS file
<!-- Fetch remote js-->
<amp-script src="https://tickers.ABC.com/hello.js"></amp-script>
<!-- js-->
<script id="ticker" type="text/plain" target="amp-script">
document.addEventListener('DOMContentLoaded', function (event) {
var ticker = new Ticker({ info: 2 });
ticker.attachToTextBox('progressive_span');
ticker.SetCurrencySign('IDR ');
ticker.tick();
});
</script>
But it seems ticker function is not loaded.
Pretty simple test app, but for some reason, the template is not rendering and so far I just try one template only. Only blank page showing. no error
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
app.AppMainView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: '#nested-viewer',
view1Template: _.template( $('#view1').html() ),
view2Template: _.template( $('#view2').html() ),
view3Template: _.template( $('#view3').html() ),
// New
// Delegated events for creating new items, and clearing completed ones.
events: {
'keyup [nv-data="myinput"]': 'changedData',
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function() {
console.log("init")
this.dataStorage1=new app.dataStorage();
console.log(this.dataStorage1)
// this.listenTo(app.Fund, 'change',this.adjustAllDivison);
},
// New
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
this.$el.html(this.view1Template());
},
changedData: function(){
console.log("changedData");
},
resetAllDivison: function(){
console.log("resetAllDivison")
},
});
// js/app.js
var app = app || {};
$(function() {
// Kick things off by creating the **App**.
new app.AppMainView();
});
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Nested View</title>
<link rel="stylesheet" href="src/app/style.css">
<link rel="stylesheet" href="/library/dragdealer/0.9.8/css/dragdealer.css">
</head>
<body>
<div id="nested-viewer">
</div>
<!-- Templates -->
<script type="text/template" id="view1">
<div class="view1s">
<input nv-data="myinput" type="text" id="input1" name="" value="123" placeholder="">
</div>
</script>
<script type="text/template" id="view2">
<div class="view2s">
<p id="display2">View 2 </p>
</div>
</script>
<script type="text/template" id="view3">
<div class="view3s">
<p id="display3">View 3</p>
</div>
</script>
<!-- Loading Templates + Vendor Scripts -->
<script type="text/template" id="item-template"></script>
<!-- Addons -->
<script src="/library/dragdealer/0.9.8/js/dragdealer.js"></script>
<!-- Main Framework -->
<script src="src/assets/lib/jquery.js"></script>
<script src="src/assets/lib/underscore.js"></script>
<script src="src/assets/lib/backbone.js"></script>
<script src="src/assets/lib/backbone.localStorage.js"></script>
<!-- Modules -->
<!-- Main -->
<!-- Nested View -->
<script src="src/app/modules/NestedView/models/dataStore.js"></script>
<script src="src/app/modules/NestedView/views/AppMainView.js"></script>
<!--
<script src="src/app/modules/NestedView/views/view1.js"></script>
<script src="src/app/modules/NestedView/views/view2.js"></script>
<script src="src/app/modules/NestedView/views/view3.js"></script>
-->
<!-- App Base -->
<script src="src/app/router.js"></script>
<script src="src/app/app.js"></script>
</body>
</html>
You actually don't append the View's el to DOM. You don't even call the view instance's render method. You could do it on initialization, i.e. in your initialize method or after creating the instance.
var mainView = new app.AppMainView();
mainView.render();
mainView.$el.appendTo(document.body);
Edit: I just noticed that you are passing a selector to the view (el: '#nested-viewer'). This means that just need to call the render method as the element exists in the DOM.
I am following this tutorial to integrate SignalR to my project http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/
So basically this is my View where I want to show my table.
#{
ViewBag.Title = "PatientInfo";
}
<h2>PatientInfo</h2>
<h3>#ViewBag.pName</h3>
<h5>#ViewBag.glucoseT</h5>
#if (Session["LogedUserFirstname"] != null)
{
<text>
<p>Welcome #Session["LogedUserFirstname"].ToString()</p>
</text>
#Html.ActionLink("Log Out", "Logout", "Home")
<div class="row">
<div class="col-md-12">
<div id="messagesTable"></div>
</div>
</div>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/SignalR/Hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
$.ajax({
url: '/home/GetMessages',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
</script>
}
My project is running but the table doesn't appear at all. I started by pasting the view because I believe that the scripts are not executed in the first place; The Alert Message is NOT being shown even if I try to add one directly after
$(function () {
alert("I am an alert box!");
This is my Layout.cshtml file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
</div>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#p_table").dataTable();
});
</script>
#RenderSection("scripts", required: false)
</body>
</html>
I am using Visual Studio 2012, MVC4.
Please Help..
Make sure you have placed all your script tags from the view inside the scripts section of the view:
#section scripts {
... your <script> tags come here
}
The reason why your alerts don't work is because you have directly put them inside the body of the view which gets rendered at the #RenderBody() call of the Layout. But as you can see it's only at the end of this Layout that we have references to the scripts such as jQuery and signalr.
Now they will appear at the proper location: #RenderSection("scripts", required: false).
By the way use the console window in your webbrowser to see potential script errors you might have. For example in your case it would display that jQuery is not defined error.
Another remark: don't include signalR script twice: right now you seem to have included jquery.signalR-2.2.0.js in your view and jquery.signalR-2.2.0.min.js in your Layout.