OpenLayers: embedding map in asp .net webpage - javascript

I have requirement to show place on map using lat and long on open street map with markers. I I have tried some code after searching in Google. But showing nothing. I am providing my code and some example link which i have tried.
<head runat="server">
<title>OpenLayers Simplest Example</title>
<script src="OpenLayers.js" type="text/javascript"></script>
<script src="osm-marker-popup.js" type="text/javascript"></script>
</head>
<body onload="init()">
<form id="form1" runat="server">
<h1 id="title">
OSM with Marker and Popup</h1>
<p id="shortdesc">
Demonstrate use of an OSM layer with a marker and a popup.
</p>
<div id="tags">
openstreetmap osm marker popup
</div>
<div id="map">
</div>
<div id="docs">
<p>
A common use case for OpenLayers is to display a marker at a location on the map,
and add some information in a popup. It is also easy to add a tooltip with a short
description. See the <a href="osm-marker-popup.js" target="_blank">osm-marker-popup.js
source</a> to see how this is done.
</p>
</div>
</form>
Code of osm-marker-popup.js
var map;
function init() {
// The overlay layer for our marker, with a simple diamond as symbol
var overlay = new OpenLayers.Layer.Vector('Overlay', {
styleMap: new OpenLayers.StyleMap({
externalGraphic: '../img/marker.png',
graphicWidth: 20, graphicHeight: 24, graphicYOffset: -24,
title: '${tooltip}'
})
});
// The location of our marker and popup. We usually think in geographic
// coordinates ('EPSG:4326'), but the map is projected ('EPSG:3857').
var myLocation = new OpenLayers.Geometry.Point(10.2, 48.9)
.transform('EPSG:4326', 'EPSG:3857');
// We add the marker with a tooltip text to the overlay
overlay.addFeatures([
new OpenLayers.Feature.Vector(myLocation, { tooltip: 'OpenLayers' })
]);
// A popup with some information about our location
var popup = new OpenLayers.Popup.FramedCloud("Popup",
myLocation.getBounds().getCenterLonLat(), null,
'<a target="_blank" href="http://openlayers.org/">We</a> ' +
'could be here.<br>Or elsewhere.', null,
true // <-- true if we want a close (X) button, false otherwise
);
// Finally we create the map
map = new OpenLayers.Map({
div: "map", projection: "EPSG:3857",
layers: [new OpenLayers.Layer.OSM(), overlay],
center: myLocation.getBounds().getCenterLonLat(), zoom: 15
});
// and add the popup to it.
map.addPopup(popup);
}
Links.
http://wiki.openstreetmap.org/wiki/OpenLayers_Simple_Example
http://wiki.openstreetmap.org/wiki/Openlayers_POI_layer_example
http://wiki.openstreetmap.org/wiki/OpenLayers_Marker

change
<script src="OpenLayers.js" type="text/javascript"></script>
to
<script src="http://openlayers.org/api/OpenLayers.js"></script>

Related

Building OpenStreetMap into a WordPress Custom Plugin

I am building a WordPress plugin that involves the use of maps and user created custom markers. I want to separate the map from the marker so that a user can create custom markers cross map platform and keep the marker data on there WordPress page.
I set up a development server on a raspberry pi 3 B, with a 2 Terabyte hard drive that it boots from. I set up an OpenStreetMap tile server of North America to practice on and I got it up and through and html file in my /var/www/html that runs through a LAMP server that also includes my WordPress development web server.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>Public Transport Lines - ÖV-Linien - openptmap.org</title>
<link rel="shortcut icon" href="favicon_pt.png">
<link rel="stylesheet" href="style.css" type="text/css">
<style> /* avoid empty tiles */ .olImageLoadError {display: none;}
</style>
<script src="OpenLayers.js" type="text/javascript"></script>
<script src="OpenStreetMap.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
function init() {
// The overlay layer for our marker, with a simple diamond as symbol
var overlay = new OpenLayers.Layer.Vector('Overlay', {
styleMap: new OpenLayers.StyleMap({
externalGraphic: '../img/marker.png',
graphicWidth: 20, graphicHeight: 24, graphicYOffset: -24,
title: '${tooltip}'
})
});
// The location of our marker and popup. We usually think in geographic
// coordinates ('EPSG:4326'), but the map is projected ('EPSG:3857').
var myLocation = new OpenLayers.Geometry.Point(10.2, 48.9)
.transform('EPSG:4326', 'EPSG:3857');
// We add the marker with a tooltip text to the overlay
overlay.addFeatures([
new OpenLayers.Feature.Vector(myLocation, {tooltip: 'OpenLayers'})
]);
// A popup with some information about our location
var popup = new OpenLayers.Popup.FramedCloud("Popup",
myLocation.getBounds().getCenterLonLat(), null,
'<a target="_blank" href="http://openlayers.org/">We</a> ' +
'could be here.<br>Or elsewhere.', null,
true // <-- true if we want a close (X) button, false otherwise
);
// Finally we create the map
map = new OpenLayers.Map({
div: "map", projection: "EPSG:3857",
layers: [new OpenLayers.Layer.OSM(), overlay],
center: myLocation.getBounds().getCenterLonLat(), zoom: 15
});
// and add the popup to it.
map.addPopup(popup);
}
</script>
</head>
<body onload="init();">
<div style="width:100%; height:100%;" id="map"></div><br></body>
</html>
This is an example of the example marker that I created which I can use a short code to link to in my plugin, but I can't get scripts to run in the plugin itself with results on the map.
For example when I run this script in my plugin attached to just a plain map.html iframe it doesn't do anything.

Google Maps: Buttons doesn't work to show marker

(I'm very noob with this. I'm learning on my own, I know my code is messy.)
I am working with Google Maps API, and I want the user to click a button (either Restaurant 1 or Restaurant 2) and then have the map pan to the location of that restaurant, using a marker and a InfoWindow above. Simple, right?
Here's my HTML code so far.
<!DOCTYPE html>
<html>
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="estilo.css">
<link rel="stylesheet" href="fuente1.css">
<link rel="stylesheet" href="fuente2.css">
<style>
html,body,h1,h2,h3,h4,h5,h6 {font-family: "Roboto", sans-serif}
</style>
<body class="w3-light-grey">
<!-- Page Container -->
<div class="w3-content w3-margin-top" style="max-width:1400px;">
<!-- The Grid -->
<div class="w3-row-padding">
<!-- Left Column -->
<div class="w3-third">
<div class="w3-white w3-text-grey w3-card-4">
<div class="w3-container">
<img><br>Choose a restaurant<p><br>
<button id="button" style="width:110px;height:30px;cursor:pointer;">Restaurant 1</button>
<button id="button2" style="width:110px;height:30px;cursor:pointer;">Restaurant 2</button>
<!-- End Left Column --> </p>
</div>
</div>
</div>
<!-- Right Column -->
<div class="w3-twothird">
<div class="w3-container w3-card w3-white w3-margin-bottom">
<h2 class="w3-text-grey w3-padding-16"><i class="fa fa-suitcase fa-fw w3-margin-right w3-xxlarge w3-text-blue"></i>
MAP
</h2><div class="w3-container">
<html>
<body>
<div id="map" style="width:555px;height:500px"></div>
<script>
function myMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(31.825948, -116.599869),
zoom: 16
});
}
function addmarker(lat, lon) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map
});
map.panTo(new google.maps.LatLng(lat, lon));
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBQ3QnkneaUIsXaJHZtYwqdWxX9KCMj4CA&callback=myMap">"></script>
</body>
</html>
<br><br>
</div>
</div>
<!-- End Right Column -->
</div>
<!-- End Grid -->
</div>
<!-- End Page Container -->
</div>
</body>
</html>
</body>
</html>
As you can see I have everything set up. The only thing that doesn't work are the buttons.
I have the following Javascript but I have no idea whatsoever on how to implement it in my HTML.
$('#button').click(function() {
addmarker('-22.3157017', '-49.0660877');
});
$('#button2').click(function() {
addmarker('-23.5936152', '-46.5856465');
});
I'll be happy to hear any lectures for this affair and any help will be greatly appreciated.
For reference, I want it to work pretty much like this one. Place marker on google maps api with html button
I did not use your markup - I've created my own.
Upon checking your javascript, everything seems well, except of these two things: missing jQuery library and the code placement of your button event handlers.
It seems you are trying to add Google Maps Javascript API Markers to these locations "-22.3157017,-49.0660877" and "-23.5936152,-46.5856465" by pressing their corresponding triggers (buttons). I would suggest doing a Reverse Geocoding before adding the markers once an event has been fired.
The term geocoding generally refers to translating a human-readable
address into a location on a map. The process of doing the converse,
translating a location on the map into a human-readable address, is
known as reverse geocoding.
You should also add jQuery as an external library to make their events such as ".click()" to work. You can download it here.
For the buttons, you should add these lines $('#button1').click(function()); and $('#button1').click(function()); inside your myMap() function.
It should look something like this:
function myMap() {
var myLatLng = {lat: 31.825948, lng: -116.599869};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$('#button1').click(function(){
var coord = { lat: parseFloat('-22.3157017'), lng: parseFloat('-49.0660877') };
addMarker( coord, map );
});
$('#button2').click(function(){
var coord = { lat: parseFloat('-23.5936152'), lng: parseFloat('-46.5856465') };
addMarker( coord, map );
});
}
On your addMarker function, add two arguments that accepts the coordinates, and the map object.
function addMarker(params, map) {);
Inside that function, create a variable geocoder and the value is a new instance of google.maps.Geocoder().
var geocoder = new google.maps.Geocoder();
With that, you can now use geocode method. Geocode method accepts two arguments: location and callback. In the location parameter, you need to supply the coordinates you acquired from the addMarker() function.
geocoder.geocode({'location' : params}, function( results, status ) {});
The callback is the part where most of our logic will be implemented. The callback accepts two arguments: results, and status. The results argument returns an array of results if the status is OK. If so, we will now iterate through each array element and then create a new Google Maps Javascript API Markers. On the markers, we'll just supply the coordinates and maps object for its position and map property.
if (status === 'OK') {
var result = results.map( function( value, index ){
map.setCenter(params);
var newMarker = new google.maps.Marker({
position : params,
map : map,
});
});
} else {
alert('Geo not successful: ' + status);
}
This line 'map.setCenter(params);' sets the position displayed by the map.
Whole code below:
<button id="button1">Restaurant 1</button>
<button id="button2">Restaurant 2</button>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=myMap">
</script>
function myMap() {
var myLatLng = {lat: 31.825948, lng: -116.599869};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$('#button1').click(function(){
var coord = { lat: parseFloat('-22.3157017'), lng: parseFloat('-49.0660877') };
addMarker( coord, map );
});
$('#button2').click(function(){
var coord = { lat: parseFloat('-23.5936152'), lng: parseFloat('-46.5856465') };
addMarker( coord, map );
});
}
function addMarker(params, map) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'location' : params}, function( results, status ) {
if (status === 'OK') {
var result = results.map( function( value, index ){
map.setCenter(params);
var newMarker = new google.maps.Marker({
position : params,
map : map,
animation: google.maps.Animation.DROP,
});
});
} else {
alert('Geo not successful: ' + status);
}
});
}
Hope it could help and happy coding!
I have answered this before on stackoverflow for how to show icons and infowindow and just updated my fiddle to use https instead. Following are very simple steps you need to take care of.
When you click on that fiddle you will see all HTML, JS and CSS I have used to show icons on map, list of people on car and interactivity to click on them to centre on map.
Using gmap3 library I have inlcuded google map on page
Using List elements I have coded location of items at <li data-gb="car" data-mapid="sc102" data-isactive="0" data-lat="53.538566" data-long="-0.327017199999951">Second Car</li> in data attributes for each item. It can be restuarants, parks etc
Important bits in code are in Javascript and these are
Events and Addmarker actions as well as logic to click on list items.
{ action: 'addMarkers',
marker:{
values:ulmarkerspeople,
options:{
draggable: false,
icon:'http://webricate.com/stackoverflow/mapicons/male-2.png'
},
events:{
mouseover: function(marker, event, context){
var listelement = jQuery("li[data-mapid='"+context.data.id+"']");
jQuery(listelement).attr('style','background-color:#ccc');
jQuery(listelement).attr('data-isactive','1');
var map = $(this).gmap3("get"),
infowindow = $(this).gmap3({get:{name:"infowindow"}});
if (infowindow){
infowindow.open(map, marker);
infowindow.setContent(context.data.ht);
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
} else {
$(this).gmap3({
infowindow:{
anchor:marker,
options:{content: context.data.ht}
}
});
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
}
},
mouseout: function(marker,event,context){
var listelement = jQuery("li[data-mapid='"+context.data.id+"']");
jQuery(listelement).attr('style','background-color:#fff');
jQuery(listelement).attr('data-isactive','0');
var infowindow = $(this).gmap3({get:{name:"infowindow"}});
if (infowindow){
infowindow.close();
jQuery("#customPopup").hide(500);
jQuery("#customPopup").html("");
}
}
}
}
}
Please read through Javascript comments on fiddle and you will get the gist of it.

leaflet geocoder and draggable marker show results in input field

Hi I am using the following https://github.com/perliedman/leaflet-control-geocoder to get the location on map. But When I get the result I want to have the option to move the marker so I can adjust the coordinates. I found a code that is moving the marker and shows the coordinates in a 2 fields but I have problem to join the two codes together. Also how I get the results coordinates to show in the two flields. I dont have much experience with leaflet maps so any help would be appreciated.
Thank you
Dany
my code:
<html lang="en">
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<link rel="stylesheet" href="assets/css/leaflet-control-geocoder.css" />
</head>
<body>
<div class="map" id="map" style="width: 600px; height: 400px"></div>
<input id="latitude" type="text" name="latitude" />
<input id="longitude" type="text" name="longitude" />
</body>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script src="assets/js/leaflet-control-geocoder.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([0, 0], 2);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
L.Control.geocoder().addTo(map);
var marker = L.marker([51.441767, 5.470247],{
draggable: true
}).addTo(map);
marker.on('dragend', function (e) {
document.getElementById('latitude').value = marker.getLatLng().lat;
document.getElementById('longitude').value = marker.getLatLng().lng;
});
</script>
</html>
Simply refer to Leaflet Control Geocoder API.
You can customize what the plugin does with the result it receives from the search request. By default it creates a (fixed) marker, binds a popup and opens it.
In your case, you could do:
var geocoder = L.Control.geocoder().addTo(map),
latInput = document.getElementById('latitude'),
lngInput = document.getElementById('longitude'),
previousMarker;
// Customize what to do from the result.
geocoder.markGeocode = function (result) {
var latlng = result.center;
// Remove previous marker if any.
if (previousMarker) {
map.removeLayer(previousMarker);
}
previousMarker = L.marker(latlng, {
draggable: true // Create a draggable marker.
}).addTo(map).
on('dragend', onDragEnd). // Attach position display.
bindPopup(result.html). // Emulate Geocoder default behaviour.
openPopup(); // bind a popup and open it right away.
displayLatLng(latlng); // Display position right away.
};
function onDragEnd(event) {
var latlng = event.target.getLatLng();
displayLatLng(latlng);
}
function displayLatLng(latlng) {
latInput.value = latlng.lat;
lngInput.value = latlng.lng;
}
Demo: http://jsfiddle.net/ve2huzxw/11/

navigationControl, mapTypeControl and scaleControl go behind the map

I am going to make an app in which there is a section to display a marked location on Google Maps. Everything works well but Google Map tools like navigationControl, mapTypeControl and scaleControl become hidden in some devices like Samsung Galaxy Tab 10.1 ( they seem to go behind the map ). Even I've changed their value to true but they are still hidden in some devices.
Here is what I've made:
<--! The HTML -->
<article class="container">
.
.
.
...( some tags go here )
<section class="span12">
<div id="mapDiv"> </div>
</section>
</article>
/*The Javascript*/
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var position = new google.maps.LatLng(38.89655520572012, -77.03372955322266);
var myOptions = {
zoom: 15,
center: position,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(
document.getElementById("mapDiv"), myOptions);
var marker = new google.maps.Marker({
position: position,
map: map,
title:"We are here.",
});
}
</script>
Does anybody know why they become hidden?!
Any help is appreciated.
Try adding {max-width: none;} to your #mapDiv. I know the Google Maps API sometimes has trouble with responsive designs. It uses sprites for the control images and Bootstrap can interfere with that.

OpenLayers, when specifying a style for layer, firefox doesnt render

When I specify the style attribute to the vector layer, firefox does not render the vectors on that layer.
To test this, just execute the included javascript and html page.
You'll see an EditingToolbar on the top right corner, try to draw a LineString with it using firefox.
What you'll discover is that the LineStrings do not appear on the layer at all.
Try to remove the styleMap attribute from the vectors layer and everything will work correctly.
If you know the reason for this problem, please let me know.
Thank you for your time and help in advance.
P.S
Also, you'll have to use your own OpenLayers library and link up to it from the html page.
Personally I'm using the latest version from GitHub because the other versions have another annoying bug:
There's a dialogue from google maps poping up constantly.
function initialize(){
new Map();
}
function Map(){
this.map;
this.editing_toolbar;
this.vectors;
this.epsg900913 = new OpenLayers.Projection('EPSG:900913');
this.epsg4326 = new OpenLayers.Projection('EPSG:4326');
this.line_control;
this.renderer;
this.line_control,this.renderer=OpenLayers.Util.getParameters(window.location.href).renderer;
this.renderer= (this.renderer) ? [this.renderer] : OpenLayers.Layer.Vector.prototype.renderers;
// Create the map object
this.map = new OpenLayers.Map('map');
//Create a Google layer
var gmap = new OpenLayers.Layer.Google(
"Google Streets", // the default
{
numZoomLevels: 30,
projection: new OpenLayers.Projection("EPSG:900913")
}
);
var my_style=new OpenLayers.StyleMap({
"default":new OpenLayers.Style({
strokeWidth:5,
fillColor:"1484e6",
strokeColor:"1484e6"
}),
"select":new OpenLayers.Style({
fillColor:"e39119",
strokeColor:"e39119"
})
});
this.vectors= new OpenLayers.Layer.Vector(
"Vector Layer",
{styleMap:my_style,
renderers:this.renderer
}
);
this.map.addLayers([gmap,this.vectors]);
this.editing_toolbar=new OpenLayers.Control.EditingToolbar(this.vectors);
this.map.addControl(this.editing_toolbar);
this.map.addControl(new OpenLayers.Control.LayerSwitcher());
this.map.addControl(new OpenLayers.Control.MousePosition());
this.map.setCenter(new OpenLayers.LonLat(-123.12, 49.28).transform(this.epsg4326, this.epsg900913), 13);
}
<html>
<head>
<title>OpenLayers: Google Layer Example</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyAt66skA87gnWvy7UQl065zFaFHNXJiBc4&sensor=false"></script>
<script type="text/javascript" src="/static/open_layers/lib/OpenLayers.js"></script>
<script type="text/javascript" src="/static/firefox_bug.js"></script>
</head>
<body onload="initialize()">
<div id="map" class="smallmap"></div>
</body>
</html>

Categories

Resources