I have created a new widget on google map using javascript and html, added a google map api(http://maps.googleapis.com/maps/api/js?key=xxx&callback=xxx) resource, but when i run it, gives error saying failed to load widget resource.
below is my code
Any help please
var map;
function initMap() {
map = new google.maps.Map(document.getElementById(
'map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
.
Related
The piece of code bellow (we all know the origin) helps you get geo coordinates.
The result is being displayed in the div called result.
What I need, is for the result to be displayed in a form field so that I can save it to my database, instead of manually typing it.
Thanks
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
The piece of code below (we all know the origin) helps you get geo coordinates.
The result is being displayed in the div called result.
What I need, is for the result to be displayed in a form field so that I can save it to my database, instead of manually typing it.
Thanks
In my electron app, a user can select one or more images for printing. To do this, I create a BrowserView which is not visible, load html into it and print it before destroying the view. This worked ok up to Electron 5. But after upgrading my app to electron 10, the printing still occurs but the image is broken (not visible). Any ideas?
Here is a sample of the HTML used to initialize my browser view:
<!DOCTYPE html>
<html>
<head>
<style>#media print { #page { margin: 0; padding: 0;} html, body { margin: 0; padding: 0; height: 100%; width: 100%; } html body *:not(.tempPrinterPaper) {display: none; visibility: hidden; z-index: -5000; } .tempPrinterPaper { display: flex; align-items: center; justify-content: center; position: relative; page-break-after: always; page-break-inside: avoid; overflow: hidden; height: 100%; width: 100%; border: none; margin: 0; padding: 0; background-color: #FFFFFF; text-align: center; align-self: stretch; } .tempPrinterPaper img.tempPrinterPaperImage { display: flex; position: relative; height: auto; max-height: 100%; max-width: 100%; margin: 0; padding: 0; z-index: 500000000000; visibility: visible; } }</style>
</head>
<body>
<div class="tempPrinterPaper"><img class="tempPrinterPaperImage" src="C:\Users\igweo\OneDrive\Pictures\rts9nzl-e1526310385107.jpg" /></div>
</body>
</html>
Here is the code for printing:
// now initialize browser window
printerWindow = new remote.BrowserView( {webPreferences: {webSecurity: false}} );
// load url
printerWindow.webContents.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(printerHTML));
// after contents have been loaded
printerWindow.webContents.on('did-finish-load', function() {
printerWindow.webContents.print({silent: false, printBackground: false}, function(res) {
// if printing is successful, show a notification
if (res) {
//let printNotification = new Notification('Image' + ((currentPrintList.length > 1) ? 's' : '') + ' successfully sent to printer', {icon: 'static/icons/logoFilledBlue.png'});
let printNotification = new Notification('Image' + ((currentPrintList.length > 1) ? 's' : '') + ' successfully sent to printer', {body: app_name});
}
// clean up print list
//currentPrintList.length = 0;
// after printing is done, destroy browser window
printerWindow.destroy();
// just to be sure :-)
printerWindow = null;
});
});
Unfortunately in electron 10, the old ways no longer seem to work. What I have now done is to create a file called print.html, then write my html contents to the file and print it from the main process.
In app.js
function showPrintDialog() {
// build html string to be printed
let printHTML = '<!DOCTYPE html><html><head><style>#media print { #page { margin: 0; padding: 0;} }</style></head><body>HELLO WORLD</body></html>';
// save file in the userdata directory
let printFilePath = app.getPath('userData') + "\\print.html";
// write to file using powershell (THIS IS ONLY FOR WINDOWS)
let cmd = ['"' + printerHTML + '" | Set-Content -Path "' + printFilePath + '"'];
let cx = cp.spawn('powershell.exe', cmd);
// wait for completion
cx.stdout.on('close', function(data) {
(async function() {
// invoke ipc function to display a dialog box and send the required parameters
let printResult = await ipcRenderer.invoke('show-print-dialog', { printFilePath: printFilePath, successMessage: 'Successfully sent to printer'});
}) ();
});
}
Also, in app.js, we need a function to show notifications when printing is completed:
ipcRenderer.on('show-notification', function(event, args) {
// show a notification
showNotification(args);
});
Now, in our main.js, we will create a browserview with the written file and call the print command. When it is done, request a notification be shown.
// show printing dialog and handle printing
ipcMain.handle('show-print-dialog', async(event, args) => {
// create a browser view
try {
// now initialize browser window
let printerWindow = new BrowserView( {webPreferences: {worldSafeExecuteJavaScript: true, contextIsolation: true}});
// At this point, there should be a file called print.html in the local app path for the user
// This should be to C:\Users\username\AppData\Roaming\Photo Viewer Classic\print.html
printerWindow.webContents.loadURL(args.printFilePath);
// after contents have been loaded
printerWindow.webContents.on('did-finish-load', async function() {
// show print dialog
printerWindow.webContents.print({silent: false, printBackground: false}, function(res) {
// if printing is successful, res will return true
if (res) {
// show notification
event.sender.send('show-notification', args.successMessage);
}
// after printing is done, destroy browser window
printerWindow.destroy();
// just to be sure :-)
printerWindow = null;
});
});
} catch (e) { console.log(e); }
// If failed, simply return false
});
This question already has answers here:
Google Maps API v3: How to remove all markers?
(32 answers)
Closed 4 years ago.
Could someone be kind enough to share how I can clear the markers in google map before refreshing it with a new set of markers?
In my map, I'm adding markers from an array that contains name, lat and long. The name can be picked from a drop down menu, and then all the markers for that name are added to the page.
Prtoject : Asp.Net Mvc
Link image: https://i.hizliresim.com/V927Py.jpg
When the user adds markers, the previous set of markers remain. I'd like to remove any existing markers before adding the new set.
After reading the documentation, I tried this:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model List<Project_Map.Models.KONUM>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Marker Icons</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<style>
#map_wrapper {
height: 700px;
}
#map_canvas {
width: 100%;
height: 100%;
}
</style>
<div id="map_wrapper">
<div class="mapping" id="map_canvas">
</div>
</div>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
jQuery(function ($) {
var script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBT56XlfxnK2OB4K93vWdrZci_CKjZyQOM&callback=initMap";
document.body.appendChild(script);
});
</script>
<!-- Google Maps Kodu -->
<script type="text/javascript">
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'<img src="#IMG_SRC#" />' +
'</div>' +
//'<h2 id="firstHeading" class="firstHeading">#PERSONEL#</h2>' +
'<div id="bodyContent">' +
'<b>Mesafe: </b>#MESAFE# Km<br />' +
'<b>Tarih: </b> #TARIH#' +
'</p>' +
'</div>' +
'</div>';
$(document).ready(function () {
initMap();
});
function initMap() {
var mapCenter = { lat: 39.684536, lng: 35.337094 };
var map = new google.maps.Map(document.getElementById('map_wrapper'), {
zoom: 6,// haritanın yakınlık derecesi
center: mapCenter, // haritanın merkezi
mapTypeId: google.maps.MapTypeId.HYBRID
});
var infoWindow = new google.maps.InfoWindow();
setInterval(function () {
$.ajax({
url: '#Url.Action("GetMapLocations", "Konum")',
type: "POST",
success: function (data) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var position = {
lat: parseFloat(json[i].lat.replace(',', '.')),
lng: parseFloat(json[i].lng.replace(',', '.'))
};
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.BOUNCE,
map: map,
});
// infoWindow içeriğini replace et
var cs = contentString;
cs = cs.replace("#PERSONEL#", json[i].name);
cs = cs.replace("#MESAFE#", json[i].mesafe);
cs = cs.replace("#TARIH#", json[i].tarih);
cs = cs.replace("#IMG_SRC#", json[i].img);
google.maps.event.addListener(marker, 'click', (function (marker, cs, infoWindow) {
return function () {
infoWindow.setContent(cs);
infoWindow.open(map, this);
passive: true;
};
})(marker, cs, infoWindow));
};
},
error: function (data) { alert("Malesef Sunucunuza Ulaşamıyoruz. Lütfen Tekrar Deneyiniz..."); },
});
}, 5000);
};
</script>
</body>
</html>
You have to set up an array, where you can store the added marker
var gmarkers = [];
If you add a marker you have to store the marker object in the array.
gmarkers.push(marker);
If you want to remove these markers you can use something like:
function removeMarker() {
if (gmarkers.length > 0) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i] != null) {
gmarkers[i].setMap(null);
}
}
}
gmarkers = [];
}
I set up a nice map in my rails application. Everything is working fine but I cannot style the map with SnazzyMaps.
Here is my map.js file:
import GMaps from 'gmaps/gmaps.js';
const mapElement = document.getElementById('map');
if (mapElement) { // don't try to build a map if there's no div#map to inject in
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
const markers = JSON.parse(mapElement.dataset.markers);
const mapMarkers = map.addMarkers(markers);
mapMarkers.forEach((marker, index) => {
marker.addListener('click', () => {
// map.setCenter(markers[index]);
markers[index].infoWindow.open(map, marker);
})
});
if (markers.length === 0) {
map.setZoom(2);
} else if (markers.length === 1) {
map.setCenter(markers[0].lat, markers[0].lng);
map.setZoom(14);
} else {
map.fitLatLngBounds(markers);
}
}
import { autocomplete } from '../components/autocomplete';
// [...]
autocomplete();
On SnazzyMaps they give the following example. My question is, where shall I insert which part of this code in my own file. Been trying it for a while now but cannot make it work. Here is SnazzyMaps example:
<!DOCTYPE html>
<html>
<head>
<title>Snazzy Maps Super Simple Example</title>
<style type="text/css">
/* Set a size for our map container, the Google Map will take up 100% of this container */
#map {
width: 750px;
height: 500px;
}
</style>
<!--
You need to include this script tag on any page that has a Google Map.
The following script tag will work when opening this example locally on your computer.
But if you use this on a localhost server or a live website you will need to include an API key.
Sign up for one here (it's free for small usage):
https://developers.google.com/maps/documentation/javascript/tutorial#api_key
After you sign up, use the following script tag with YOUR_GOOGLE_API_KEY replaced with your actual key.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY"></script>
-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 11,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(40.6700, -73.9400), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [{"featureType":"all","elementType":"geometry.fill","stylers":[{"weight":"2.00"}]},{"featureType":"all","elementType":"geometry.stroke","stylers":[{"color":"#9c9c9c"}]},{"featureType":"all","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"color":"#eeeeee"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#7b7b7b"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#c8d7d4"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#070707"}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]}]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.6700, -73.9400),
map: map,
title: 'Snazzy!'
});
}
</script>
</head>
<body>
<h1>Snazzy Maps Super Simple Example</h1>
<h2>WY</h2>
<!-- The element that will contain our Google Map. This is used in both the Javascript and CSS above. -->
<div id="map"></div>
</body>
</html>
To set the style using Gmaps library, you need to define the styles and then set it to the current map as below:
const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
var styles = [
{
stylers: [
{ hue: "#00ffe6" },
{ saturation: -20 }
]
}, {
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
}, {
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
map.addStyle({
styledMapName:"Styled Map",
styles: styles,
mapTypeId: "map_style"
});
map.setStyle("map_style");
Reference:
https://github.com/hpneo/gmaps/blob/master/examples/styled_maps.html
I'm not exactly sure on how to use this external library, it seems I need to make another request to get the markers to show up but I'm not sure of the best way to do it in mvc.
Error I am getting is: MarkerLabel_.getSharedCross is not a function
Points just contains an array of Lats/Lngs
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: points[0],
zoom: 10
});
for (var i = 0; i < points.length; i++) {
var marker = new MarkerWithLabel({
position: points[i],
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75},
icon: "../Content/Images/map-icon.png"
});
marker.setMap(map);
}
}
<script src="https://maps.googleapis.com/maps/api/js?key=MyKey&callback=initMap"
async defer></script>
<script src="~/Scripts/Custom/marker-with-label.js"></script>