Socket.io ERR_EMPTY_RESPONSE laravel mix - vuejs2

I'm new to laravel mix, and i'm currently working in a project with laravel 7.30.9 and vue 2.6.14.
This project uses redis and socket.io. I've never used them before.
I've already installed redis in my machine (I'm using windows by the way). I've instaled laravel-echo and socket.io with npm dependencies with --save
npm install laravel-echo-server socket.io-client --save
First I run laravel-echo-server start, then I run php artisan queue:work and finally I run php artisan serve.
So I'm trying to run it locally but I keep getting the same error:
GET http://localhost:6001/socket.io/socket.io.js net::ERR_EMPTY_RESPONSE
This is the bootstrap.js error
Error: Socket.io client not found. Should be globally available or passed via options.client
This is my welcome.blade.php, the error apears before the console.log(window.location.hostname) line inside the second script
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#200;600&display=swap" rel="stylesheet">
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 200;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.content {
text-align: center;
}
.title {
font-size: 84px;
}
.links > a {
color: #636b6f;
padding: 0 25px;
font-size: 13px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.m-b-md {
margin-bottom: 30px;
}
</style>
</head>
<body>
<div id="app">
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
Laravel Echo Test Mao
</div>
<div id="chat-notification"></div>
</div>
</div>
</div>
<script src="/app-assets/vendors/js/vendors.min.js"></script>
<script>
window.laravelEchoPort = '{{ env('LARAVEL_ECHO_PORT') }}'
console.log(window.location.hostname);
</script>
<script src="//{{ request()->getHost() }}:{{ env('LARAVEL_ECHO_PORT') }}/socket.io/socket.io.js"></script>
<script src="{{ asset('js/app-vue.js') }}"></script>
<script>
const userId = '{{ auth()->id() }}'
window.Echo.channel('public-message-channel')
.listen('.MessageEvent', (data) => {
$("#chat-notification").append(`<div class="alert alert-warning">`+data.message+`</div>`);
});
window.Echo.private('message-channel.'+ userId)
.listen('.MessageEvent', (data) => {
$("#chat-notification").append(`<div class="alert alert-danger">`+data.message+`</div>`);
});
</script>
</body>
</html>
This is my app-vue.js
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
import { EchoPrivate } from './bootstrap';
window.EchoPrivate = EchoPrivate;
window.Vue = require('vue');
import VueFormWizard from 'vue-form-wizard'
import 'vue-form-wizard/dist/vue-form-wizard.min.css'
Vue.use(VueFormWizard)
import CxltToastr from 'cxlt-vue2-toastr'
Vue.use(CxltToastr)
import 'cxlt-vue2-toastr/dist/css/cxlt-vue2-toastr.css';
import Vuesax from 'vuesax';
import 'vuesax/dist/vuesax.css';
import 'material-icons/iconfont/material-icons.css';
Vue.use(Vuesax);
import SmartTable from 'vuejs-smart-table'
Vue.use(SmartTable)
var VueScrollTo = require('vue-scrollto');
Vue.use(VueScrollTo)
import VueTheMask from 'vue-the-mask'
Vue.use(VueTheMask)
import money from 'v-money'
Vue.use(money, { precision: 3 })
import SkeletonCards from 'vue-ultimate-skeleton-cards'
Vue.use(SkeletonCards)
import CKEditor from '#ckeditor/ckeditor5-vue2';
Vue.use(CKEditor);
import VoerroTagsInput from '#voerro/vue-tagsinput';
Vue.component('tags-input', VoerroTagsInput);
import { formatValue, formatCurrency, fullFormatValue } from './trm';
Vue.filter('currency', formatCurrency);
import Gate from './components/permissions/Gate';
// Vue.prototype.$gate = new Gate(window.user);
Vue.prototype.$gate = new Gate(window.user);
window.formatValue = formatValue;
window.currency = formatCurrency;
window.fullFormatValue = fullFormatValue;
/*COMPONENTES EXTERNOS*/
Vue.component('input-form', require('./components/InputFormComponent.vue').default);
Vue.component('changued-password', require('./components/components/user/ChangedPassword.vue').default)
Vue.component('preview-doc', require('./components/components/previewdoc/PreviewDoc.vue').default)
Vue.component('custom-repetear', require('./components/components/vue-repeater/src/components/repeater.vue').default)
Vue.component('currency-display', require('./components/currency/CurrencyDisplay.vue').default)
Vue.component('currency-list', require('./components/currency/CurrencyList.vue').default)
Vue.component('filter-date', require('./components/components/filters/FilterDate.vue').default)
/*=============================================
COMPONENTES
=============================================*/
Vue.component('cards-statistcs-projects', require('./components/components/cardsStatiscsProjects/CardsStatistcsProjects.vue').default);
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('invoice-project', require('./components/backend/pages/project/components/invoice/InvoiceProject.vue').default);
Vue.component('type-invoice', require('./components/backend/pages/project/components/invoice/TypeInvoice.vue').default);
Vue.component('items-invoice', require('./components/backend/pages/project/components/invoice/components/ItemsInvoice.vue').default);
Vue.component('create-invoice-project', require('./components/backend/pages/project/components/invoice/components/CreateInvoice.vue').default);
/*=============================================
COMPONENTES GLOBALES
=============================================*/
Vue.component('show-project-component', require('./components/components/project/ShowProject.vue').default);
Vue.component('show-customer-component', require('./components/components/customer/ShowCustomer.vue').default);
// BEGIN: Profile
Vue.component('edit-profile', require('./components/backend/pages/profile/EditProfileUser.vue').default);
// END: Profile
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
import VueInternationalization from 'vue-i18n';
import Locale from './vue-i18n-locales.generated';
import Vue from "vue";
window.Vue.use(VueInternationalization);
const i18n = new VueInternationalization({
locale: window.lang,
messages: Locale
});
window.eventBus = new Vue();
const appVue = new Vue({
el: '#app',
i18n
});
And this is my bootstrap.js:
window._ = require('lodash');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
// window.Popper = require('popper.js').default;
// window.$ = window.jQuery = require('jquery');
//
// require('bootstrap');
} catch (e) { }
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
import Echo from 'laravel-echo';
let echo = null;
try {
echo = new Echo({
broadcaster: 'socket.io',
host: `${window.location.hostname}:${window.laravelEchoPort}`,
// host: "creategicalatina.test:6001",
transports: ['websocket']
});
let init = false;
echo.connector.socket.on('connect', function () {
if (init) {
setTimeout(() => {
Pace.stop();
}, 500)
} else {
init = true;
}
});
echo.connector.socket.on('disconnect', function () {
console.log('disconnected');
});
echo.connector.socket.on('reconnecting', function (attemptNumber) {
console.log('reconnecting', attemptNumber);
});
} catch (error) {
console.log('init echo: ', error);
}
window.Echo = echo;
const channels = {};
export const EchoPrivate = (channel_name, listen_name, callback) => {
if (!echo) {
return;
}
const key_channel = btoa(channel_name);
if (!channels[key_channel]) {
channels[key_channel] = {
socket: null,
listens: {}
}
try {
channels[key_channel] = {
socket: echo.private(channel_name),
listens: {}
}
} catch (error) {
console.log('channel: ', error);
}
}
const channel = channels[key_channel];
if (!channel.socket) {
return;
}
const key_listen = btoa(listen_name);
if (!channel.listens[key_listen]) {
channel.listens[key_listen] = {
callbacks: [],
listen: function (e) {
this.callbacks.forEach(c => c(e));
}
};
try {
channel.socket.listen(listen_name, (e) => {
channel.listens[key_listen].listen(e);
})
} catch (error) {
console.log('listing: ', error);
}
}
channel.listens[key_listen].callbacks.push(callback);
}
Finally this is my .env file
APP_NAME="app"
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=https://localhost
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
LARAVEL_ECHO_PORT=6001
And my laravel-echo-server.json
{
"authHost": "https://127.0.0.1:8000",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": "127.0.0.1",
"port": "6001",
"protocol": "https",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "/Users/jimmy/.config/valet/Certificates/app.test.crt",
"sslKeyPath": "/Users/jimmy/.config/valet/Certificates/app.test.key",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
I really apreciate any kind of help :].

Related

SvelteKit w/ MSAL.js redirecting automatically for login page

I have an application which is running SvelteKit and MSAL.js, nothing else. I have created a component file for my MSAL instance, you can see that below:
<script context="module">
import * as msal from "#azure/msal-browser";
let signInType = "redirect";
export let accountId = "";
const loginRequest = {
scopes: ["User.Read"],
cache: msal.CacheLookupPolicy.Default,
};
const msalConfig = {
auth: {
clientId: "<client-id>",
authority:
"https://login.microsoftonline.com/<tenant-id>",
redirectUri: "http://localhost:5173/profile",
navigateToLoginRequestUrl: true,
clientSecret: "<secret>",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
};
export const currentUser = msalConfig.accountId;
const msalInstance = new msal.PublicClientApplication(msalConfig);
console.dir(msalInstance);
msalInstance
.handleRedirectPromise()
.then(handleResponse)
.catch((err) => {
console.error(err);
});
function handleResponse(resp) {
if (resp !== null) {
accountId = resp.account.homeAccountId;
msalInstance.setActiveAccount(resp.account);
} else {
// need to call getAccount here?
const currentAccounts = msalInstance.getAllAccounts();
if (!currentAccounts || currentAccounts.length < 1) {
return;
} else if (currentAccounts.length > 1) {
// Add choose account code here
} else if (currentAccounts.length === 1) {
const activeAccount = currentAccounts[0];
msalInstance.setActiveAccount(activeAccount);
accountId = activeAccount.homeAccountId;
}
}
}
export async function signIn(method) {
if (signInType === "popup") {
return msalInstance
.loginPopup(loginRequest)
.then(handleResponse)
.catch(function (error) {
console.log(error);
});
} else if (signInType === "redirect") {
return msalInstance.loginRedirect(loginRequest);
}
}
export async function signOut(interactionType) {
const logoutRequest = {
account: msalInstance.getAccountByHomeId(accountId),
};
if (interactionType === "popup") {
msalInstance.logoutPopup(logoutRequest).then(() => {
window.location.reload();
});
} else {
msalInstance.logoutRedirect(logoutRequest);
}
}
</script>
Then I exported my signIn function to my login page, and I created my login button succesfully, using the function from my MSAL instance. The first thing I want to create in my profile page, is the logout but whenever I export any function or variable from MSAL instance to profile page, when the profile page is loaded, it just redirect automatically to my http://localhost:5173, and doesn't stay in http://localhost:5173/profile page.
This is my http://localhost:5173 page:
<script lang="ts">
import MSAL, { signIn } from "../lib/Components/MSAL.svelte";
</script>
<div class="mainContainer">
<div class="title">
<h1>Welcome!</h1>
</div>
<div class="btns">
<button on:click={signIn}>Login</button>
</div>
</div>
<style>
* {
margin: 0;
padding: 0;
}
.mainContainer {
background: url(<link to my image>)
no-repeat center center/cover;
z-index: 1;
box-shadow: inset 50px 60px 250px #ffffff,
inset -50px -60px 120px #ffffff;
height: 100vh;
}
.title {
text-align: center;
padding-top: 7rem;
}
.title h1 {
font-size: 100px;
color: rgba(130, 255, 255, 0.658);
}
.btns {
display: flex;
justify-content: center;
margin-top: 10rem;
}
button {
border: 1px black solid;
border-radius: 15px;
width: 100px;
height: 40px;
}
.btns :hover {
background-color: rgba(130, 255, 255, 0.664);
color: white;
}
</style>
And this is my profile page:
<script lang="ts">
import TopAppBar from "../../lib/Components/TopAppBar.svelte";
import BottomAppBar from "../../lib/Components/BottomAppBar.svelte";
import MSAL, { signOut } from "../../lib/Components/MSAL.svelte";
</script>
<div class="topBar">
<TopAppBar />
</div>
<div>
<button on:click={signOut}>Logout</button>
</div>
<div class="bottomBar">
<BottomAppBar />
</div>
<style>
* {
margin: 0;
padding: 0;
}
.bottomBar {
position: fixed;
z-index: 100;
bottom: 0;
left: 0;
width: 100%;
}
</style>
When I inspect the page, there isn't any error.
Do you guys have any clue why this is happening?
I tried to export my function in different ways but always the same problem. Also added
<script context="module">
But nothing has changed.
I can't do much because there is no error. I'm just expecting that when I login to my system, it doesn't back to my http://localhost:5173, and stays in http://localhost:5173/profile

Why is it that Apache behaves differently on 304 responses when requestiong from browser against requesting from Node.js?

I created this repository to investigate why my custom headers were not being sent to the client when the response code is 304.
I had previously read answers to this question, which explains why headers are not sent on a 304 response. However, I noticed something strange. I ran the tests below against the same application (observing x-test-header, which I generate randomly for every request), first directly to the application, then via Apache reverse proxy. Interestingly, they behaved the same. I received a different header on both cases even when I receive a 304 status code
const chaiHttp = require('chai-http');
const chai = require('chai');
const assert = chai.assert;
const server = require('../main');
chai.use(chaiHttp);
suite("chai etag support", () => {
test("repeating a request to /data with if-none-match should give 304", async () => {
let res = await chai
.request(server)
.get('/data');
const etag = res.get('etag');
res = await chai
.request(server)
.get('/data')
.set('if-none-match', etag);
assert.equal(res.status, 304);
});
});
function behaviourTest(server, suiteName) {
suite(suiteName, function() {
test('Two subsequent GET /data requests should give the same etag', async () => {
const firstRequest = await chai
.request(server)
.get('/data');
const secondRequest = await chai
.request(server)
.get('/data');
assert.notEqual(secondRequest.get('x-test-header'), firstRequest.get('x-test-header'), "x-test-headers should be different");
assert.equal(secondRequest.get('etag'), firstRequest.get('etag'), "Etags should be the same");
const etag = secondRequest.get('etag');
const thirdRequest = await chai
.request(server)
.get('/data')
.set('if-none-match', etag);
assert.equal(thirdRequest.status, 304);
assert.notEqual(thirdRequest.get('x-test-header'), secondRequest.get('x-test-header'), "x-test-headers should be different");
});
});
}
behaviourTest(process.env.URL, 'Without reverse proxy');
behaviourTest(process.env.REVERSE_PROXY_URL, 'With reverse proxy');
The above got me to assume that Apache is sending the headers every time. I then ran basically the same tests but inside an HTML page. Only then did the requests via the reverse proxy fail to send an updated x-test-header value. Or maybe it got sent, and the browser ignored it and used the value from the cache.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etag Test</title>
<style>
.full-screen {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.vh-align {
display: flex;
align-items: center;
justify-content: center;
}
#div-results {
width: 360px;
min-height: 400px;
font-family: 'Courier New', Courier, monospace;
border: 1px solid #ccc;
border-radius: 2px;
overflow-y: auto;
background-color: black;
color: white;
padding: 20px;
}
.red-text {
color: red;
}
.green-text {
color: green;
}
</style>
</head>
<body>
<div class="full-screen vh-align">
<div id="div-results">
TEST RESULTS
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.3.6/chai.min.js" integrity="sha512-sP7hp2cpEWsmOHQPc6taNuXFmvG59BhI3YS3tOvZ+nDEqOyyORLiY3nBjLkWgCNI8SFZ5koUyiBO42Q3wzZDrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function getHeadersFromFetchAPIResponse(res) {
const keys = Array.from(res.headers.keys());
const headers = {};
for (let i in keys) {
const key = keys[i]
headers[key] = res.headers.get(key);
}
return headers;
}
async function test(url, suiteName) {
let icon, message = '';
try {
const firstRes = await fetch(`${url}/data`);
const secondRes = await fetch(`${url}/data`);
assert.equal(firstRes.headers.get('etag'), secondRes.headers.get('etag'),);
assert.notEqual(firstRes.headers.get('x-test-header'), secondRes.headers.get('x-test-header'));
icon = tick;
} catch (err) {
icon = xMark;
message = `<br>${tab}${String(err)}`;
console.log(err);
}
document.getElementById('div-results').innerHTML += `<br>${icon} ${suiteName}${message}`;
}
const { assert } = chai;
const proxiedUrl = window.prompt("Reverse proxied url");
const url = window.prompt("URL without proxy");
const tick = '<span class="green-text">✓</span>';
const xMark = '<span class="red-text">✗</span>';
const tab = ' ';
(async () => {
await test(url, "No reverse proxy");
await test(proxiedUrl, "Reverse proxy");
})();
</script>
</body>
</html>
Why am I getting different behaviors in Node instead of the browser?

Electron + Vite project cannot show png resource

I am using Vite + Electron to make a desktop app demo.
But it cannot load png resource, but js, css resource is fine. So it worked like this
png canoot be loaded
when I check the console, it shows: Failed to load resource: net::ERR_FILE_NOT_FOUND
Also, the url of the png is weird:
it is not even a common file path
So what happened really ???
Here is my code:
vite.config.js
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
base: path.resolve(__dirname, './dist/'),
plugins: [vue()]
})
index.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
webSecurity: false,
}
})
win.loadFile('dist/index.html')
win.webContents.openDevTools()
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
App.vue
<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<img alt="Vue logo" src="/src/assets/logo.png" />
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
I know perhaps this problem sounds silly, but I just start it and Vue,JS... are really not my comfort zone. So if anyone could help me, I will really appreciate it.

arcgis goTo feature and open popup

I am new to Arcgis maps and using ArcGIS Javascript 4.2 library. Currently the features are showing up on the map and I am trying to go to feature and open it's popup programmatically. below is my code to query the features which is working fine.
var query = layer.createQuery();
query.where = "key= " + dataItem.key+ "";
query.returnGeometry = true;
query.returnCentroid = true;
query.returnQueryGeometry = true;
layer.queryFeatures(query).then(function (results) {
//I am getting the feature results here.
//trying to navigate to feature and open popup
});
Note: I tried using the following code from documentation which is working fine but I don't have the center as the features are polylines in my case.
view.goTo({center: [-126, 49]})
First, View goTo method has several options, including just using a geometry wich I think would be a better option for your case, zoom to a polyline.
Second to open the popup you just need to use the open method and you can pass there the features to show.
Check this example I put for you, has both suggestions,
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>ArcGIS API for JavaScript Hello World App</title>
<style>
html,
body {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
#selectDiv {
height: 30px;
width: 100%;
margin: 5px;
}
#cableNameSelect {
height: 30px;
width: 300px;
}
#cableGoToButton {
height: 30px;
width: 100px;
}
#viewDiv {
height: 500px;
width: 100%;
}
</style>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/css/main.css">
</head>
<body>
<div id="selectDiv">
<select id="cableNameSelect"></select>
<button id="cableGoToButton">GO TO</button>
</div>
<div id="viewDiv">
</div>
<script src="https://js.arcgis.com/4.15/"></script>
<script>
require([
'esri/Map',
'esri/views/MapView',
'esri/layers/FeatureLayer'
], function (Map, MapView, FeatureLayer) {
const cableNameSelect = document.getElementById("cableNameSelect");
const cableGoToButton = document.getElementById("cableGoToButton");
const map = new Map({
basemap: 'hybrid'
});
const view = new MapView({
container: 'viewDiv',
map: map,
zoom: 10,
center: {
latitude: 47.4452,
longitude: -121.4234
}
});
view.popup.set("dockOptions", {
buttonEnabled: false,
position: "top-right"
});
const layer = new FeatureLayer({
url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/ArcGIS/rest/services/cables/FeatureServer/0",
popupTemplate: {
title: "{NAME}",
outFields: ["*"],
content: [{
type: 'fields',
fieldInfos: [
{
fieldName: "length"
},
{
fieldName: "owners"
},
{
fieldName: "rfs"
}
]
}],
}
});
map.add(layer);
layer.queryFeatures({
where: "1=1",
outFields: ["Name"],
returnGeometry: false
}).then(function(results) {
for(const graphic of results.features) {
cableNameSelect.appendChild(new Option(graphic.attributes.Name, graphic.attributes.Name));
}
});
cableGoToButton.onclick = function() {
if (!cableNameSelect.value) {
return;
}
cableGoToButton.disabled = true;
layer.queryFeatures({
where: `Name='${cableNameSelect.value}'`,
outFields: ["*"],
returnGeometry: true
}).then(function (results) {
cableGoToButton.disabled = false;
if (!results.features) {
return;
}
view.goTo(results.features[0].geometry);
view.popup.open({
features: [results.features[0]]
})
})
};
});
</script>
</body>
</html>

Map won't show right in Joomla

I have the following code of a map using api google, I have tested the code in several html editor and its work perfectly, but when i upload in my web page doesn’t work. The map appears all zoomed in some random point in the ocean. I create an article in Joomla 1.5.20, paste the code. Its shows right in the preview but not in the web page. I disable filtering and use none editor and still won’t work. Thanks for the help.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBInlv7FuwtKGhzBP0oISDoB2Iu79HNrPU&sensor=false">
</script>
<script type="text/javascript">
var map;
// lets define some vars to make things easier later
var kml = {
a: {
name: "Productor",
url: "https://maps.google.hn/maps/ms?authuser=0&vps=2&hl=es&ie=UTF8&msa=0&output=kml&msid=200984447026903306654.0004c934a224eca7c3ad4"
},
b: {
name: "A&S",
url: "https://maps.google.hn/maps/ms?ie=UTF8&authuser=0&msa=0&output=kml&msid=200984447026903306654.0004c94bac74cf2304c71"
}
// keep adding more if ye like
};
// initialize our goo
function initializeMap() {
var options = {
center: new google.maps.LatLng(13.324182,-87.080071),
zoom: 9,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map_canvas"), options);
var ctaLayer = new google.maps.KmlLayer('https://maps.google.hn/maps/ms?authuser=0&vps=5&hl=es&ie=UTF8&oe=UTF8&msa=0&output=kml&msid=200984447026903306654.0004c94bc3bce6f638aa1');
ctaLayer.setMap(map);
var ctaLayer = new google.maps.KmlLayer('https://maps.google.hn/maps/ms?authuser=0&vps=2&ie=UTF8&msa=0&output=kml&msid=200984447026903306654.0004c94ec7e838242b67d');
ctaLayer.setMap(map);
createTogglers();
};
google.maps.event.addDomListener(window, 'load', initializeMap);
// the important function... kml[id].xxxxx refers back to the top
function toggleKML(checked, id) {
if (checked) {
var layer = new google.maps.KmlLayer(kml[id].url, {
preserveViewport: true,
suppressInfoWindows: true
});
google.maps.event.addListener(layer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.description;
showInContentWindow(text);
});
function showInContentWindow(text) {
var sidediv = document.getElementById('content_window');
sidediv.innerHTML = text;
}
// store kml as obj
kml[id].obj = layer;
kml[id].obj.setMap(map);
}
else {
kml[id].obj.setMap(null);
delete kml[id].obj;
}
};
// create the controls dynamically because it's easier, really
function createTogglers() {
var html = "<form><ul>";
for (var prop in kml) {
html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
" onclick='highlight(this,\"selector-" + prop + "\"); toggleKML(this.checked, this.id)' \/>" +
kml[prop].name + "<\/li>";
}
html += "<li class='control'><a href='#' onclick='removeAll();return false;'>" +
"Limpiar el Mapa<\/a><\/li>" +
"<\/ul><\/form>";
document.getElementById("toggle_box").innerHTML = html;
};
// easy way to remove all objects
function removeAll() {
for (var prop in kml) {
if (kml[prop].obj) {
kml[prop].obj.setMap(null);
delete kml[prop].obj;
}
}
};
// Append Class on Select
function highlight(box, listitem) {
var selected = 'selected';
var normal = 'normal';
document.getElementById(listitem).className = (box.checked ? selected: normal);
};
</script>
<style type="text/css">
.selected { font-weight: bold; }
</style>
</head>
<body>
<div id="map_canvas" style="width: 80%; height: 400px; float:left"></div>
<div id="toggle_box" style="position: absolute; top: 100px; right: 640px; padding: 10px; background: #fff; z-index: 5; "></div>
<div id="content_window" style="width:10%; height:10%; float:left"></div>
</body>
</html>
The problem was solve using dropbox to host the KML files insted google maps.