I am trying to create a custom google map just like this.
How do I put my own map picture and erase rest of the google map?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100%; z-index: 0;}
#gmnoprint {width: auto;}
</style>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>my custom map</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function CustomMapType() {
}
CustomMapType.prototype.tileSize = new google.maps.Size(256,256);
CustomMapType.prototype.maxZoom = 5;
CustomMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
var div = ownerDocument.createElement('DIV');
var baseURL = 'tiles/';
baseURL +=zoom + '_' + coord.x + '-' + coord.y + '.png';
div.style.width = this.tileSize.width + 'px';
div.style.height = this.tileSize.height + 'px';
div.style.backgroundColor = '#89919E';
div.style.backgroundImage = 'url(' + baseURL + ')';
return div;
};
CustomMapType.prototype.name = "Custom";
CustomMapType.prototype.alt = "Tile Coordinate Map Type";
var map;
var CustomMapType = new CustomMapType();
function initialize() {
var mapOptions = {
minZoom: 2,
maxZoom: 5,
isPng: true,
mapTypeControl: false,
streetViewControl: false,
center: new google.maps.LatLng(65.07,-56.08),
zoom: 3,
mapTypeControlOptions: {
mapTypeIds: ['custom', google.maps.MapTypeId.ROADMAP],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
map.mapTypes.set('custom',CustomMapType);
map.setMapTypeId('custom');
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="background: #1B2D33;"></div>
</body>
</html>
use that code and put the tiles into the folder output =)
Related
I have a dataset with different points on a map, stored on GitHub as a GeoJSON. I would like to assign popups to each point of that dataset, that would display some of its data attributes when clicked. I managed to copy some code from Mapbox tutorials but I don't know how to connect my points from the GeoJSON file with the markers.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.marker {
background-image: url(https://placekitten.com/g/);
background-size: cover;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
}
.mapboxgl-popup {
max-width: 200px;
}
.mapboxgl-popup-content {
text-align: center;
font-family: 'Open Sans', sans-serif;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiamFua29tYWciLCJhIjoiY2ozNmNhMXQyMDQ4czMybzl6YTN2cDM0ciJ9.naD_i9iNOl_CEZ3WkY8Nvg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-96, 37.8],
zoom: 3
});
map.addSource('worldcities_points', {
type: 'geojson',
data: 'https://github.com/jankomag/worldcitiespopchange/blob/master/readycities_geojson.geojson'
});
// add markers to map
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(https://placekitten.com/g/' + marker.properties.iconSize.join('/') + '/)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.addEventListener('click', function() {
window.alert(marker.properties.message);
});
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
});
</script>
</body>
</html>
First off, I would recommend you not to share your access token. Others can use it and you will be billed. As you already have shared it, probably a good idea to disable it.
I have some comments to your code:
You are adding a source. In order to show it on the map, you would have to create a layer for it and add it to the map.
map.addSource('worldcities_points', {
type: 'geojson',
data: 'https://github.com/jankomag/worldcitiespopchange/blob/master/readycities_geojson.geojson'
});
--> To add it as a layer:
// Add a layer showing the places.
map.addLayer({
'id': 'worldcities_points',
'type': 'symbol',
'source': 'worldcities_points',
'layout': {
'icon-image': '{icon}-15',
'icon-allow-overlap': true
}
});
You can try to add the popups to the map after you have created them for your objects:
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
// Open the popup when mouse hover over the position of the object
map.on('mouseenter', 'places', function(e) {
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;// assuming your source geoJSON contains properties.descriptions
// Ensure that if the map is zoomed out such that multiple
// copies of the feature are visible, the popup appears
// over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
// Populate the popup and set its coordinates
// based on the feature found.
popup
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
// remove the popup when the mouse leaves the position of the object
map.on('mouseleave', 'places', function() {
map.getCanvas().style.cursor = '';
popup.remove();
});
That should get you popups! Let me know if you have questions!
I'm trying to run this example code in my browser, so I saved the code at index.html at my computer, and while opening it at my browser I got nothing in the screen, with the below error at the console:
Uncaught SyntaxError: Unexpected identifier . line 13
Line 13 is:
import Map from 'ol/Map.js';
how can I fix it?
Thanks to #Mike, I rewrote it as below, and it worked:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v5.3.0/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v5.3.0/build/ol.js"></script>
<title>OpenLayers example</title>
</head>
<body>
<h2>My Map</h2>
<div id="map" class="map"></div>
<script type="text/javascript">
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var imageStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({color: 'yellow'}),
stroke: new ol.style.Stroke({color: 'red', width: 1})
})
});
var headInnerImageStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: 2,
fill: new ol.style.Fill({color: 'blue'})
})
});
var headOuterImageStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({color: 'black'})
})
});
var n = 200;
var omegaTheta = 30000; // Rotation period in ms
var R = 7e6;
var r = 2e6;
var p = 2e6;
map.on('postcompose', function(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
var theta = 2 * Math.PI * frameState.time / omegaTheta;
var coordinates = [];
var i;
for (i = 0; i < n; ++i) {
var t = theta + 2 * Math.PI * i / n;
var x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r);
var y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r);
coordinates.push([x, y]);
}
vectorContext.setStyle(imageStyle);
vectorContext.drawGeometry(new ol.geom.MultiPoint(coordinates));
var headPoint = new ol.geom.Point(coordinates[coordinates.length - 1]);
vectorContext.setStyle(headOuterImageStyle);
vectorContext.drawGeometry(headPoint);
vectorContext.setStyle(headInnerImageStyle);
vectorContext.drawGeometry(headPoint);
map.render();
});
map.render();
</script>
</body>
</html>
use this:
<html lang="en">
<head>
<title>Map</title>
<!-- -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol.css" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/ol-geocoder#latest/dist/ol-geocoder.min.css" rel="stylesheet">
<!-- -->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ol-geocoder"></script>
<script type="text/javascript">
var layersGroup= new ol.layer.Tile({
title : 'OSM',
type : 'base',
visible : false,
source : new ol.source.OSM()
});
mapView = new ol.View({
center: [8415526,1301999],
zoom: 17
});
Printmap = new ol.Map({
layers: layersGroup ,
target: 'printmap',
view: mapView
});
</script>
</head>
<body>
<div class="page-container">
<div id="printmap" class="printmap"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>D3.js GoogleMap Voronoi Diagram</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://shimz.me/example/d3js/geo_example/geo_template/topojson.v0.min.js"> </script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<style type="text/css">
html, body{
margin: 0px;
padding: 0px;
}
html, body, #map_canvas {
width: 100%;
height: 100%;
}
.SvgOverlay {
position: relative;
width: 900px;
height: 600px;
}
.SvgOverlay svg {
position: absolute;
top: -4000px;
left: -4000px;
width: 8000px;
height: 8000px;
}
</style>
</head>
<body>
<div id="map_canvas"></div>
<br>
<script type="text/javascript">
d3.json('bus-stops.json', function(pointjson){
main(pointjson);
});
function main(pointjson) {
//Google Map
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(1.290270,103.851959),
});
var overlay = new google.maps.OverlayView(); //OverLay
overlay.onAdd = function () {
var layer = d3.select(this.getPanes().overlayLayer).append("div").attr("class", "SvgOverlay");
var svg = layer.append("svg");
var svgoverlay = svg.append("g").attr("class", "AdminDivisions");
overlay.draw = function () {
var markerOverlay = this;
var overlayProjection = markerOverlay.getProjection();
//Google Map
var googleMapProjection = function (coordinates) {
var googleCoordinates = new google.maps.LatLng(coordinates[1], coordinates[0]);
var pixelCoordinates = overlayProjection.fromLatLngToDivPixel(googleCoordinates);
return [pixelCoordinates.x + 4000, pixelCoordinates.y + 4000];
}
var pointdata = pointjson.lat;
console.log(pointdata);
var positions = [];
pointdata.forEach(function(d) {
positions.push(googleMapProjection(d.lat,d.lng));
});
var polygons = d3.geom.voronoi(positions);
var pathAttr ={
"d":function(d, i) { return "M" + polygons[i].join("L") + "Z"},
stroke:"red",
fill:"none"
};
svgoverlay.selectAll("path")
.data(pointdata)
.attr(pathAttr)
.enter()
.append("svg:path")
.attr("class", "cell")
.attr(pathAttr)
var circleAttr = {
"cx":function(d, i) { return positions[i][0]; },
"cy":function(d, i) { return positions[i][1]; },
"r":2,
fill:"red"
}
svgoverlay.selectAll("circle")
.data(pointdata)
.attr(circleAttr)
.enter()
.append("svg:circle")
.attr(circleAttr)
};
};
overlay.setMap(map);
};
</script>
</body>
</html>
The data file is of the structure:
[{"no":"10009","lat":"1.28210155945393","lng":"103.81722480263163",
"name":"Bt Merah Int"},
{"no":"10011","lat":"1.2777380589964","lng":"103.83749709165197",
"name":"Opp New Bridge Rd Ter"}]
It is also giving an error in console:
TypeError: pointdata is undefined. I am trying to plot using the example: http://bl.ocks.org/shimizu/5610671
I am getting undefined for pointjson using console.log(). Please suggest how do I get the co-ordinate values in pointjson
I am trying to simply get a marker to display. I'm using Google's examples as a guide because this is the first time I am using Google Maps API. I can't find any syntax problems with the code below. Why is it not loading the marker?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100%; z-index: 0;}
#gmnoprint {width: auto;}
</style>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Map of Floor Plan</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function CustomMapType() {
}
CustomMapType.prototype.tileSize = new google.maps.Size(256,256);
CustomMapType.prototype.maxZoom = 4;
CustomMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
var div = ownerDocument.createElement('DIV');
var baseURL = 'C:/Temp';
baseURL += zoom + '_' + coord.x + '_' + coord.y + '.png';
div.style.width = this.tileSize.width + 'px';
div.style.height = this.tileSize.height + 'px';
div.style.backgroundColor = '#1B2D33';
div.style.backgroundImage = 'url(' + baseURL + ')';
return div;
};
CustomMapType.prototype.name = "Custom";
CustomMapType.prototype.alt = "Tile Coordinate Map Type";
var map;
var CustomMapType = new CustomMapType();
function initialize() {
var myLatlng = new google.maps.LatLng(65, -56);
var mapOptions = {
minZoom: 0,
maxZoom: 4,
isPng: true,
mapTypeControl: false,
streetViewControl: false,
center: new google.maps.LatLng(65.07,-56.08),
zoom: 3,
mapTypeControlOptions: {
mapTypeIds: ['custom', google.maps.MapTypeId.ROADMAP],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
};
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World'
});
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
map.mapTypes.set('custom',CustomMapType);
map.setMapTypeId('custom');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="background: #1B2D33;"></div>
</body>
</html>
Your map is not initialized at time when marker is created:
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World'
});
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
So, you have to create map first and then use it:
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World'
});
or call setMap on the marker after initializing the map:
var marker = new google.maps.Marker({
position: myLatlng,
title: 'Hello World'
});
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
marker.setMap(map);
I'm currently using the Google Maps API for the first time.
Essentially I wish to have the map zoomed out so that the whole world is displayed with no overlap (e.g. bits of a certain country are not repeated on either side of the map).
The closest I have found to my requirements is this SO question:
Google Maps API V3: Show the whole world
However, the top answer on this question does not provide the full code required.
I have used the starter example from Google as the base for my HTML:
<!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="https://maps.googleapis.com/maps/api/js?key=AIzaSyCuP_BOi6lD7L6ZY7JTXRdhY1YEj_gcEP0&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 1
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
However, in the example provided in the question above a number of additional variables have been specified. My question is, where do I plug in the code from the question above to ensure that my world map is displayed correctly?
If you don't want any repeats, you need to control the minimum zoom allowed and the width of your map to be less than or equal to one width of of the base tiles at the minimum zoom level allowed on your map.
At zoom zero, one width of the world is a single 256 x 256 pixel tile, each zoom level increases that by a factor of 2.
This will show one width of the map at zoom level 1 (512x512 map-canvas), you can change the height, but the width will need to be 256 at zoom 0, 512 at zoom 1, 1024 at zoom 2, etc:
<!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: 512px; width:512px;}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 1,
minZoom: 1
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
code snippet:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 1,
minZoom: 1
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map-canvas {
height: 512px;
width: 512px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>
Here's a function worldViewFit I like to use:
function initMap() {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
minZoom: 1
};
map = new google.maps.Map(document.getElementById('officeMap'), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
//Map is ready
worldViewFit(map);
});
}
function worldViewFit(mapObj) {
var worldBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(70.4043,-143.5291), //Top-left
new google.maps.LatLng(-46.11251, 163.4288) //Bottom-right
);
mapObj.fitBounds(worldBounds, 0);
var actualBounds = mapObj.getBounds();
if(actualBounds.getSouthWest().lng() == -180 && actualBounds.getNorthEast().lng() == 180) {
mapObj.setZoom(mapObj.getZoom()+1);
}
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#officeMap {
height: 512px;
width: 512px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="officeMap"></div>
This is the JavaScript I found:
/**
* All locations map scripts
*/
jQuery(function($){
$(document).ready(function(){
loadmap();
});
function loadmap()
{
var locations = wpsl_locator_all.locations;
var mapstyles = wpsl_locator.mapstyles;
var mappin = ( wpsl_locator.mappin ) ? wpsl_locator.mappin : '';
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap',
mapTypeControl: false,
zoom: 8,
styles: mapstyles,
panControl : false
}
if ( wpsl_locator.custom_map_options === '1' ) mapOptions = wpsl_locator.map_options;
var infoWindow = new google.maps.InfoWindow(), marker, i;
var map = new google.maps.Map( document.getElementById('alllocationsmap'), mapOptions );
// Loop through array of markers & place each one on the map
for( i = 0; i < locations.length; i++ ) {
var position = new google.maps.LatLng(locations[i].latitude, locations[i].longitude);
bounds.extend(position);
var marker = new google.maps.Marker({
position: position,
map: map,
title: locations[i].title,
icon: mappin
});
// Info window for each marker
google.maps.event.addListener(marker, 'click', (function(marker, i){
return function() {
infoWindow.setContent(locations[i].infowindow);
infoWindow.open(map, marker);
wpsl_all_locations_marker_clicked(marker, infoWindow)
}
})(marker, i));
// Center the Map
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
if ( locations.length < 2 ) {
map.setZoom(13);
}
google.maps.event.removeListener(listener);
});
}
// Fit the map bounds to all the pins
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
google.maps.event.removeListener(boundsListener);
});
wpsl_all_locations_rendered(map);
} // loadmap()
});