Map loads incorrectly with Angular-Leaflet-Directive - html

Good morning!
I have a web application, where I use a leafletjs map (http://tombatossals.github.io/angular-leaflet-directive/#!/) and openstreetmap as tile.
The map works perfectly, I can interact in any way (add markers, create layers, zoom ..), however, when I access the page where the map is, it does not load correctly, according to the printscreen below:
It resets when I resize the window or open and close the console.
Font:
View:
<div class="col-md-12">
<div class="box_whiteframe_map">
<leaflet ng-init="vm.buscaEnderecoClientesEmpresas()" center="vm.center" defaults="vm.defaults" markers="vm.markers" width="100%" height="480px"></leaflet>
</div>
CSS/SASS:
.box_whiteframe_map {
background-color: #fff;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2), 0 1px 1px 0 rgba(0, 0, 0, .14), 0 2px 1px -1px rgba(0, 0, 0, .12);
color: #000;
margin: 0;
clear: both;
}
Controller:
/* MAP */
vm.markers = new Array();
vm.buscaEnderecoClientesEmpresas = function() {
vm.items = loadSaas(Cookies.get('crm_o2_hash')); // carregar saas id
vm.items.then(function(items) { // ler array de retorno
vm.saasid = items;
var dados = {
'saasid': vm.saasid
}
relatoriosService.carregarEnderecoClientesEmpresas(dados).then(function(response) {
if (response.data != 'null') {
vm.enderecoClientesEmpresas = response.data;
angular.forEach(vm.enderecoClientesEmpresas, function(value, key) {
if (value.tipo == 'p'){
var icon = 'user';
} else {
var icon = 'cog';
}
vm.markers.push({
group: value.cidade,
lat: value.lat_lng.lat,
lng: value.lat_lng.lng,
message: value.nome,
icon: {
type: 'awesomeMarker',
icon: icon,
markerColor: 'blue'
},
label: {
options: {
noHide: true
}
}
});
});
} else {
vm.enderecoClientesEmpresas = '';
}
}, function(error) {
console.log('Erro findSemEmail: ', error);
});
});
}
angular.extend(vm, { // EXTEND THE PROPERTIES OF MAP (MARKERS, INITIAL LOCATION..)
center: { // INITIAL LOCATION .
lat: -22.952419,
lng: -43.211667,
zoom: 4
},
defaults: {
tileLayer: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
zoomControlPosition: 'topright',
tileLayerOptions: {
opacity: 0.9,
detectRetina: true,
reuseTiles: true,
attribution: '© OpenStreetMap | &copy Funil PRÓ',
},
scrollWheelZoom: true,
minZoom: 3,
worldCopyJump: true
}
});
/* MAP FINAL */
Any help?
[]'s

You need to refresh the map:
leafletData.getMap().then(function(map) {
setTimeout(function() {
map.invalidateSize();
map._resetView(map.getCenter(), map.getZoom(), true);
}, 200);
});
In additionally, you need to inject leafletData to controller.

You need to add leaflet css
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css">

Related

How to show a popup when I click on a marker openlayers

I have made some markers on my map, each marker represents a report sent from that location.
I want to do that when I click on a specific marker I'll have its information on a popup.
The info is stored in a SQL database and it contains Category, Title, Remarks(Description), statUrgence(Urgence) & images Path(path). You can see it in the code as #_Data.Category ...
Code:
<link rel="stylesheet" href="~/css/ol.css">
<link rel="stylesheet" href="~/css/ol-ext.css">
<script src="~/js/ol.js"></script>
<div id="map" style="position: fixed; top: 62.5px; left: 0; bottom: 65px; right: 0; z-index:-1"></div>
<style>
.ol-zoom {
top: 2.5%;
}
</style>
<script type="text/javascript">
var layers = [new ol.layer.Tile({ source: new ol.source.OSM() })];
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 5,
center: [166326, 5992663]
}),
interactions: ol.interaction.defaults({ altShiftDragRotate: false, pinchRotate: false }),
layers: layers
});
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
//Tried to make here that when a marker is clicked something will happen, wasn't much of a success
// Vector Feature Popup logic
map.on('click', function (e) {
map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
console.log(feature, layer);
})
})
</script>
#{
if (Model != null)
{
foreach (var _Data in Model)
{
#*Saving the data that needs to be in each marker*#
#*<div class="card" id="overlay-container-#_Data.Id" style="display:none;">
<div class="card-header">
<h3><u>Category</u>: #_Data.category</h3><br />
<h5><u>Title</u>: #_Data.title</h5>
</div><br />
<div class="card-body">
<p>
<u>Description</u>: <br />#_Data.remarks
</p><br />
<u>Urgence</u>: #_Data.statUrgence <br />
</div>
<div class="card-footer">
#_Data.path
</div>
</div>*#
<script>
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png'
})
})
});
map.addLayer(markers);
var marker = new ol.Feature(new ol.geom.Point([parseFloat(#_Data.coordLat), parseFloat(#_Data.coordLong)]));
markers.getSource().addFeature(marker);
</script>
}
}
}
Include the properties you need in the popup as properties of the features, then you can copy them to the popup as required, as with name in https://openlayers.org/en/latest/examples/icon.html Complex popups can be created and styled as in https://openlayers.org/en/latest/examples/popup.html
End result of that using a simple subset of your properties and no extra css
<!DOCTYPE html>
<html>
<head>
<title>Popup</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#main/dist/en/v7.1.0/ol/ol.css" />
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#main/dist/en/v7.1.0/ol/dist/ol.js"></script>
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.ol-popup {
position: absolute;
background-color: white;
-webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
padding: 15px;
border-radius: 10px;
border: 1px solid #cccccc;
bottom: 12px;
left: -50px;
min-width: 280px;
}
.ol-popup:after, .ol-popup:before {
top: 100%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.ol-popup:after {
border-top-color: white;
border-width: 10px;
left: 48px;
margin-left: -10px;
}
.ol-popup:before {
border-top-color: #cccccc;
border-width: 11px;
left: 48px;
margin-left: -11px;
}
.ol-popup-closer {
text-decoration: none;
position: absolute;
top: 2px;
right: 8px;
}
.ol-popup-closer:after {
content: "✖";
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<div id="popup" class="ol-popup">
<div id="popup-content"></div>
</div>
<script>
/**
* Elements that make up the popup.
*/
const container = document.getElementById('popup');
const content = document.getElementById('popup-content');
const closer = document.getElementById('popup-closer');
/**
* Create an overlay to anchor the popup to the map.
*/
const overlay = new ol.Overlay({
element: container,
autoPan: {
animation: {
duration: 250,
},
},
});
/**
* Add a click handler to hide the popup.
* #return {boolean} Don't follow the href.
*/
closer.onclick = function() {
overlay.setPosition(undefined);
closer.blur();
return false;
};
const Model = [
{
category: 'Capital city',
title: 'London',
long: -0.12755,
lat: 51.507222,
description: 'UK capital',
},
{
category: 'Capital city',
title: 'Rome',
long: 12.5,
lat: 41.9,
description: 'Italy capital',
},
{
category: 'Capital city',
title: 'Bern',
long: 7.4458,
lat: 46.95,
description: 'Switzerland capital',
},
];
/**
* Create the map.
*/
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
],
overlays: [overlay],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([7.5, 47]),
zoom: 3,
}),
});
const features = [];
for (key in Model)
{
const _Data = Model[key];
const feature = new ol.Feature({
geometry: new ol.geom.Point(
ol.proj.fromLonLat([parseFloat(_Data.long), parseFloat(_Data.lat)])
),
category: _Data.category,
title: _Data.title,
description: _Data.description,
});
features.push(feature);
}
const markers = new ol.layer.Vector({
source: new ol.source.Vector({
features: features,
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png',
}),
}),
});
map.addLayer(markers);
map.on('click', function (evt) {
const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature) {
const coordinates = feature.getGeometry().getCoordinates();
content.innerHTML =
'<p>Category:</p><code>' + feature.get('category') + '</code><br>' +
'<p>Title:</p><code>' + feature.get('title') + '</code><br>' +
'<p>Description:</p><code>' + feature.get('description') + '</code>'
overlay.setPosition(coordinates);
}
});
</script>
</body>
</html>

Google Maps SearchBox not searching in bounds

I'm having problems getting google's searchbox service to run properly for me.
What I have is a map with a polygon drawn on it. I would like to use the searchbox and/or autocomplete service to return ONLY business of the specified type (e.g. restaurants, fast food, warehouses, etc.) that are within this polygons boundaries.
I can use the nearby service to return results based on type or keyword. I can also get the searchbox to return results for restaurants; however, if I update the search to look for other businesses, such as warehouses, the map zooms out and shows warehouses all over the world.
Here is a working fiddle example:
<html>
<head>
<meta charset="utf-8">
<title>Transition Center Online</title>
<meta name="description" content="">
<meta name="title" content="">
<meta name="author" content="WWRF">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#map {
height: 600px;
width: 100%;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div class="container">
<p>TODO: Add Google JavaScript Map with walkroute outline.</p>
<p>TODO: List walking times</p>
<p>TODO: List common walk routes and businesses</p>
<!-- where the map will live -->
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
</div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var wwrf = {
lat: 37.682319,
lng: -97.333311
};
map = new google.maps.Map(document.getElementById('map'), {
center: wwrf,
zoom: 14
});
var squareCoords = [
{lat: 37.697465, lng: -97.341629},
{lat: 37.697636, lng: -97.317306},
{lat: 37.671759, lng: -97.317142},
{lat: 37.673308, lng: -97.352833},
{lat: 37.693239, lng: -97.352852}
];
// Construct the walkroute polygon.
var walkRoute = new google.maps.Polygon({
paths: squareCoords,
strokeColor: '#008000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#008000',
fillOpacity: 0.1
});
walkRoute.setMap(map);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
//keyword: ['restaurant']
}, callback);
var walkRouteBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(37.673308, -97.352833),
new google.maps.LatLng(37.697636, -97.317306),
);
var options = {
bounds: walkRouteBounds,
strictBounds: true
};
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, options);
map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
searchBox.setBounds(walkRouteBounds);
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(37.673308, -97.352833),
new google.maps.LatLng(37.697636, -97.317306),
);
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
//icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<strong>' + place.name + '</strong><br/>' + place.formatted_address);
infowindow.open(map, this);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api&libraries=places&callback=initMap" async defer></script>
</body>
GoogleMap searchbox fiddle
EDIT: Alright so I have been able to come up with a solution using a dropdown box, although it is not ideal because I have to hard code my keywords.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Walkroute Dropdown</title>
<meta name="description" content="">
<meta name="title" content="">
<meta name="author" content="WWRF">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#map {
height: 600px;
width: 100%;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div class="container">
<select name="mapchange" onchange="updateMap(this.options[this.selectedIndex].value)">
<option value="restaurants">Restaurants</option>
<option value="warehouses">Warehouses</option>
<option value="temp services">Temp Services</option>
</select>
<!-- where the map will live -->
<div id="map"></div>
</div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
var wwrf = {
lat: 37.682319,
lng: -97.333311
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: wwrf,
zoom: 14
});
var squareCoords = [
{lat: 37.697465, lng: -97.341629},
{lat: 37.697636, lng: -97.317306},
{lat: 37.671759, lng: -97.317142},
{lat: 37.673308, lng: -97.352833},
{lat: 37.693239, lng: -97.352852}
];
// Construct the walkroute polygon.
var walkRoute = new google.maps.Polygon({
paths: squareCoords,
strokeColor: '#008000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#008000',
fillOpacity: 0.1
});
walkRoute.setMap(map);
infowindow = new google.maps.InfoWindow();
/*var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
keyword: ['restaurant']
}, callback);*/
}
var markers = [];
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
// Create a marker for each place.
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<strong>' + place.name + '</strong><br/>' + place.formatted_address);
infowindow.open(map, this);
});
}
function updateMap(selectControl) {
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var keyword = selectControl;
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
keyword: keyword
}, callback);
}
function clearMarkers() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api&libraries=places&callback=initMap" async defer></script>
</body>
</html>
And here's a link to the fiddle: Walkroute dropdown
I can see that you try to initialize the SearchBox with strictBounds: true option, but unfortunately, the SearchBox doesn't support strict bounds filter at current moment. If you can switch to the Autocomplete, it is indeed supports strict bounds and you can initialize the autocomplete like
var options = {
bounds: walkRouteBounds,
strictBounds: true,
types: ['establishment']
};
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input, options);
Regarding the strict bounds for SearchBox, there is a feature request in Google issue tracker:
https://issuetracker.google.com/issues/67982212
Feel free to star the feature request to add your vote and subscribe to notifications.
Ok ,I've been looking to this for a while and here comes a possible solution that I thought:
So inside the For loop in the callback Function may I suggest before creating a marker to ask (with a IF and I think there is a method called contains that returns a boolean) if the
place.geometry.location is inside your bounds, so if the place is not inside your bounds then you do not create that marker, therefore the map won't zoom out.
Another solution would be forcing the zoom to a value after the autocomplete search.
I hope with this you could find a solution to your issue.

how to add my location button to google map

i would like to add my location button to my map like the real google map does.
ihave tried some plugins but they didnt had location button, what should i do?
here is one plugin that i used:
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var GeoMarker = new GeolocationMarker(map);
For web browsers you can use the html5 built in geolocation to get your location: You can follow this doc: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
But first set a default location in case the browser doesn't support Geolocation
var myLocation = {lat: -34.397, lng: 150.644};
After that in your init function you can get your location like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
Set your location's coordinates as default center of the map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
Then just call this function if you want to go back to your location
function goToMyLocation() {
map.setCenter(myLocation);
}
Check this working example: https://jsbin.com/ricebu/edit?html,css,js,output
Here is the code snippet as well
var map;
var btnLocation = document.getElementById("btn-location");
var myLocation = {
lat: -34.397,
lng: 150.644
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
// I just added a marker for you to verify your location
var marker = new google.maps.Marker({
position: myLocation,
map: map
});
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
console.log(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
btnLocation.addEventListener('click', function() {
goToMyLocation();
});
function goToMyLocation() {
map.setCenter(myLocation);
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#btn-location {
position: absolute;
right: 20px;
top: 20px;
z-index: 1;
padding: 20px;
border: none;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.8);
transition: 0.5s;
}
#btn-location:hover {
background-color: rgba(0, 0, 0, 1);
color: white;
cursor: pointer;
}
<html>
<head>
<title>Location</title>
</head>
<body>
<button id="btn-location">Go to my Location</button>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&callback=initMap"></script>
</body>
</html>
var btnLocation = document.getElementById("btn-location");
var myLocation = {
lat: -34.397,
lng: 150.644
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
// I just added a marker for you to verify your location
var marker = new google.maps.Marker({
position: myLocation,
map: map
});
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
console.log(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
btnLocation.addEventListener('click', function() {
goToMyLocation();
});
function goToMyLocation() {
map.setCenter(myLocation);
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#btn-location {
position: absolute;
right: 20px;
top: 20px;
z-index: 1;
padding: 20px;
border: none;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.8);
transition: 0.5s;
}
#btn-location:hover {
background-color: rgba(0, 0, 0, 1);
color: white;
cursor: pointer;
}
<html>
<head>
<title>Location</title>
</head>
<body>
<button id="btn-location">Go to my Location</button>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&callback=initMap"></script>
</body>
</html>
You can also consider using https://www.npmjs.com/package/google-maps-current-location
It adds the typical button to the map, it handles the geolocation, and it also adds the blue circle surrounding the marker.
Hope it helps :)

Save Map Instance outside of Google Maps

I've made a google maps API (HTML) script that created markers when the user clicks on the map. I've also integrated Google+ login functions so users are unique and have profiles. I now want to make it so users can create their markers on their desired positions and then save the map so they can come back to it later. I however don't want them to use this "https://developers.google.com/maps/documentation/javascript/examples/save-widget" provided function because then the markers are synched to their google+. In other words I only want the markers to save to my website, not to their personal google maps. How would I go about saving the state of the map only on my site?
Heres the fiddle of my code: https://jsfiddle.net/hgvsurt5/
Heres the code:
<head>
<style>
#map-canvas {
width: 900px;
height: 600px;
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<title>Places search box</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initialize() {
var marker = []
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */
(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */
(input));
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
</script>
<script>
var map;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:900px;height:600px;"></div>
</body>
You must somehow bring the desired data into a format which may be sended and stored. A good approach would be to use a Data-layer to draw the features on the map, you may easily use the method toGeoJson of the Data-layer to convert the data into a geoJson and send it to a server(where you store the data).
A simple implementation:
function initialize() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
noClear: true
}),
//this may be the stored data
data = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-0.120850, 51.508742]
},
"properties": {}
}]
},
win = new google.maps.InfoWindow,
//some buttons for interaction
ctrl = document.getElementById('datactrl'),
fx = {
'data-save': {
click: function() {
//use this method to store the data somewhere,
//e.g. send it to a server
map.data.toGeoJson(function(json) {
data = json;
});
}
},
'data-show': {
click: function() {
alert('you may send this JSON-string to a server and store it there:\n\n' +
JSON.stringify(data))
}
},
'data-load': {
click: function() {
//use this method to load the data from somwhere
//e.g. from a server via loadGeoJson
map.data.forEach(function(f) {
map.data.remove(f);
});
map.data.addGeoJson(data)
},
init: true
},
'data-clear': {
click: function() {
//use this method to clear the data
//when you also want to remove the data on the server
//send a geoJSON with empty features-array to the server
map.data.forEach(function(f) {
map.data.remove(f);
});
data = {
type: "FeatureCollection",
features: []
};
}
}
};
for (var id in fx) {
var o = ctrl.querySelector('input[id=' + id + ']');
google.maps.event.addDomListener(o, 'click', fx[id].click);
if (fx[id].init) {
google.maps.event.trigger(o, 'click');
}
}
map.controls[google.maps.ControlPosition.TOP_CENTER].push(ctrl);
function placeMarker(location) {
var feature = new google.maps.Data.Feature({
geometry: location
});
map.data.add(feature);
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map.data, 'click', function(e) {
if (e.feature.getGeometry().getType() === 'Point') {
win.setOptions({
content: 'Latitude: ' + e.feature.getGeometry().get().lat() +
'<br>Longitude: ' + e.feature.getGeometry().get().lng(),
pixelOffset: new google.maps.Size(0, -40),
map: map,
position: e.feature.getGeometry().get()
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googleMap {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="googleMap">
<div id="datactrl">
<input type="button" id="data-save" value="save" />
<input type="button" id="data-show" value="show saved data" />
<input type="button" id="data-load" value="load saved data" />
<input type="button" id="data-clear" value="remove all data" />
</div>
</div>

Toggle custom labels on and off in Google Maps V3

Added some labels to my Google Map (v3), ideally I'd like two things:
1) To be able to switch them on and off (as when zoomed out the labels become cluttered)
2) To be able to change the textsize of the label depending up the mapzoom.
I added the labels like so, info being read in from some nested arrays:
for (x = 0; x < areadata.length; x++){//Start Label Loop
labelObjects[x] = new MapLabel({
text: areadata [x][0],
position: new google.maps.LatLng(areadata [x][2], areadata [x][1]),
map: mymap,
fontSize: 16,
align: 'center'
});
labelObjects[x].set('position', new google.maps.LatLng(areadata [x][2], areadata [x][1]));
}
I'm using the maplabel-compiled.js from http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/examples/maplabel.html - with one change however. mapPane.appendChild has been amended to floatPane.appendChild - this brings all labels in front of any Polygons I have on the map.
This works just fine, the problem comes when I try to control the labels, I've tried interacting with the first label in the array like so with no joy:
labelObjects[0].setVisible(false);
labelObjects[0].set('visible', false);
labelObjects[0].set('fontSize', 48);
Anyone had similar issues? Thanks for reading.
be sure that labelObjects is accessible in the scope where try to toggle the mapLabel
there is no method setVisible for a MapLabel
setting a visible-property of a MapLabel will not have any effect. To show/hide the MapLabel set the map-property of the MapLabel to either a google.maps.Map-instance(mymap) or null
var areadata = [
['label#1', 1, 1],
['label#2', 2, 2]
],
labelObjects = [],
mymap;
function init() {
var myLatlng = new google.maps.LatLng(1.5, 1.5),
myOptions = {
zoom: 7,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
mymap = new google.maps.Map(document.getElementById('map'), myOptions);
for (x = 0; x < areadata.length; x++) { //Start Label Loop
labelObjects[x] = new MapLabel({
text: areadata[x][0],
position: new google.maps.LatLng(areadata[x][2], areadata[x][1]),
map: mymap,
fontSize: 16,
align: 'center'
});
labelObjects[x].set('position', new google.maps.LatLng(areadata[x][2], areadata[x][1]));
}
mymap.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('toggle'));
}
google.maps.event.addDomListener(window, 'load', init);
body,
html,
#map {
margin: 0;
padding: 0;
height: 100%;
}
#toggle {
padding: 1px 6px;
border: 1px solid rgba(0, 0, 0, 0.15);
box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
border-radius:2px;
background: #fff;
cursor: pointer;
margin:4px;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/js-map-label#1.0.1/src/maplabel.js"></script>
<div id="map"></div>
<a id="toggle" onclick="labelObjects[0].setMap((labelObjects[0].getMap())?null:mymap)">toggle label#1</a>