Action/Select a Location in OSM Map and Show Marker - javascript

I am new to OSM API. (Open Street Map)
I'm currently searching for a solution to select (or highlight) a vector in a OpenLayers.
i.e am trying to set a location for user. That user can give his location by clicking on map (Particular location) and then need to do some manipulation with those longitude and latitude.
JS Code i have tried
function showVehicleMap(){
ltArray = document.getElementById('deviceMonitorRightPaneForm:lat').value.split(",");
lgArray = document.getElementById('deviceMonitorRightPaneForm:lon').value.split(",");
directionArray = document.getElementById('deviceMonitorRightPaneForm:direction').value.split(",");
map = createMap("deviceMap");
for(var i=0;i<ltArray.length;i++)
{
var lonLat = new OpenLayers.LonLat( lgArray[i] ,ltArray[i] ).transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
map.getProjectionObject() // to Spherical Mercator Projection
);
pointsArray.push(lonLat);
}
//prepare mid point
var latAvg = document.getElementById('deviceMonitorRightPaneForm:latAvg').value;
var lonAvg = document.getElementById('deviceMonitorRightPaneForm:lonAvg').value;
var midpoint = new OpenLayers.LonLat(lonAvg,latAvg).transform( fromProjection, toProjection);
//create Marker
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
//prepare list of markers
markers = addMarkersByDirection(markers, pointsArray, directionArray);
map.zoomToExtent(markers.getDataExtent());
map.setCenter (midpoint, 9);
//
/* ]]> */
}
How do i achieve it?

Register a mouse click event to get the position via the mouse:
map.events.register('click', map, function handleMapClick(e) {
var clickedLonLat = map.getLonLatFromViewPortPx(e.xy).transform(map.projection, map.displayProjection);
...
// place a OpenLayers.Layer.Marker at clickedLonLat for visual feedback
// for convenience: map.panTo(clicketLonLat);
...
});

Related

leaflet route360 using as input point geojson layer?

hello I have read this examples about leaflet route 360 services.
is very interests but that examples work with static coordinates,my question is how to can use this services using some point GeoJSON layer ?
my GeoJSON layer example:
coords = [];
var points = new L.GeoJSON.AJAX("{% url 'mylayer' %}",{
onEachFeature:function (feature,layer) {
coords.push(feature.geometry.coordinates.reverse());
layer.on('click', function (e) {
var field1=document.getElementById('f1');
field1.innerHTML=e.target.feature.properties.name;
});
layer.bindPopup(feature.properties.name.toString())
}
});
points.addTo(map);
leaflet route 360 example :
<script>
// define a pair of coordinates, where the map should be centered
// and should serve a the source for polygonization
var latlon = [52.51, 13.37];
// add the map and set the initial center to berlin
var map = L.map('map').setView(latlon, 14);
map.attributionControl.addAttribution("ÖPNV Daten © <a href='https://www.vbb.de/de/index.html' target='_blank'>VBB</a>");
// initialise the base map
r360.basemap({ style: 'basic', apikey: '__your-route360-api-key__' }).addTo(map);
// create the marker and add it to the map
var marker = L.marker((latlon)).addTo(map);
// create the layer to add the polygons
var polygonLayer = r360.leafletPolygonLayer().addTo(map);
// you need to define some options for the polygon service
// for more travel options check out the other tutorials
var travelOptions = r360.travelOptions();
// please contact us and request your own key if you don't already have one
travelOptions.setServiceKey('__your-route360-api-key__');
// set the service url for your area
travelOptions.setServiceUrl('https://service.route360.net/germany/');
// we only have one source which is the marker we just added
travelOptions.addSource(marker);
// we want to have polygons for 10 to 30 minutes
travelOptions.setTravelTimes([600, 1200, 1800]);
// go by foot
travelOptions.setTravelType('walk');
// call the r360°- service
r360.PolygonService.getTravelTimePolygons(travelOptions, function(polygons){
// add the returned polygons to the polygon layer
// and zoom the map to fit the polygons perfectly
polygonLayer.clearAndAddLayers(polygons, true);
});
</script>

JavaScript closure triggers all inside the loop when registering OpenLayers event even with anonymous function or bind

I have following code where I'm trying to add some markers to OpenStreetMaps and onClick they would trigger their own popup. lonLats is an array that has objects with properties lon, lat and text. Code is roughly the following.
<div id="mapdiv"></div>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script>
var map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var projection = new OpenLayers.Projection("EPSG:4326"); // transform from WGS 1984
var mapProjection = map.getProjectionObject(); // // to Spherical Mercator Projection
var zoom=16;
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
map.setCenter (new OpenLayers.LonLat(lonLats[0].lon, lonLats[1].lat).transform(projection, mapProjection), zoom);
lonLats.forEach(function(el){
var lonLat = new OpenLayers.LonLat(el.lon, el.lat).transform(projection, mapProjection);
var marker = new OpenLayers.Marker(lonLat);
markers.addMarker(marker);
var popup = new OpenLayers.Popup.FramedCloud("",
marker.lonlat,
new OpenLayers.Size(200, 200),
el.text,
null, true);
(function(p, m){
map.addPopup(p);
p.hide();
map.events.register('click', m, (function(){
this.show();
}).bind(p, null));
})(popup, marker);
});
</script>
So basically when I click on one of the markers, all popups turn visible. It seems like the classic JavaScript closure trap, but how should I register the OpenLayers event so that it only triggers the one marker I'm clicking?
The issue was rather simple, I just needed to register the event to the marker instead. Don't know how I got that mixed up from the examples, might've been confused as the the marker itself is given as a parameter.
m.events.register('click', m, (function(){
this.show();
}).bind(p, null));

Google Maps with cluster of markers and their info window

I have a cluster of Google map marker’s. I am showing Google maps in a ModalPopupExtender on a button click. After map is loaded with marker’s I want to pop up info window on mouse over of marker’s. how can I keep the details of info window of each marker when map is loading with marker’s?.
$('#map-canvas').fadeIn('slow', function() {
google.maps.event.trigger(map, 'resize');
for (var i = 0; i < asGridselectedRows.length; i++) {
var row = asGridselectedRows[i];
var Latitude = asGridMasterTable.getCellByColumnUniqueName(row, "Latitude");
var Longitude = asGridMasterTable.getCellByColumnUniqueName(row, "Longitude");
var messno = asGridMasterTable.getCellByColumnUniqueName(row, "MessNo");
var messnumber = messno.innerHTML.substring(6, messno.innerHTML.length - 7);
var Lat = Latitude.innerHTML.substring(6, Latitude.innerHTML.length - 7);
var Long = Longitude.innerHTML.substring(6, Longitude.innerHTML.length - 7);
var myLatLng = new google.maps.LatLng(Lat, Long);
map.setCenter(myLatLng);
map.setZoom(13);
marker = new google.maps.Marker({
map: map
});
if (messnumber == '00')
{
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
}
else
{
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}
marker.setPosition(myLatLng);
marker.setVisible(true);
}
});
You need to build the info window as part of the event listener. See the example given in the answer here: Changing data in the info window with Google Map markers
You can add attributes to each marker so that these can be referenced in the hover event. In your case it looks like you could simply use the messno as an attribute and then reference your data table with the marker info in

google maps API3 drawing custom map icon based on user selection

Im working on a google maps plugin (there's always room for another right?) and I'm drawing a preview of the map my users will be inserting into their content. Im able to draw everything I set out to, custom content in the info window, setting the location (through places.Autocomplete) etc. The one thing that is escaping me is custom map icon isn't being drawn.
My goal is to have the default icon drawn on first load, and then update it when it changes
Im not getting any 404 or errors in the console, and I've checked my event handlers and they are all working. Can anyone tell me where I've going astray?
Here is what I have so far:
//Initilize the map
google.maps.event.addDomListener(window, 'load', initialize);
function initialize(infowindow) {
var init_center = new google.maps.LatLng(43.703793, -72.326187);
mapOptions = {
center: init_center,
zoom: parseFloat(mapZoomReturn),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel : false,
};
var input = document.getElementById('mapAddress');
var autocomplete = new google.maps.places.Autocomplete(input);
var infowindow = new google.maps.InfoWindow();
//var marker = new google.maps.Marker({
// position: init_center,
// map: map,
// icon: mapMarkerImageReturn
//});
// Draw the map
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// marker needs to be set after the map
var marker = new google.maps.Marker({
position: init_center,
map: map,
icon: mapMarkerImageReturn
});
// Set up event listeners
// Info window DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapInfoWindow'),
'change', function() {
mapInfoWindowReturn = escape(jQuery('#mapInfoWindow').val());
// get the extra content from feild, by this time the place_changed even will have fired at least once, so we have these values
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn); // returns formatted markup for info bubble
infowindow.setContent(infowindowPlace);
});
// Marker dropdown selection DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapMarker'), 'change', update_maker);
// Custom marker text field DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapMarkerImage'), 'change', update_maker );
function update_maker(){
//update the marker imge - (not working)
markerImage = get_marker_image(); // returns URL as string
marker.setIcon(markerImage);
marker.setPosition(locPlace.geometry.location);
marker.setMap(map);
}
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn);
infowindow.close();
if (mapMarkerImageReturn !=='' || mapMarkerImageReturn !== false) marker.setVisible(false);
input.className = '';
locPlace = autocomplete.getPlace();
if (!locPlace.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (locPlace.geometry.viewport) {
map.fitBounds(locPlace.geometry.viewport);
mapCurrCenter = map.getCenter();
} else {
map.setCenter(locPlace.geometry.location);
map.setZoom(parseFloat(mapZoomReturn));
mapCurrCenter = map.getCenter();
}
// Set the marker image (not working)
markerImage = get_marker_image(); // returns URL as string
marker.setIcon(markerImage);
marker.setPosition(locPlace.geometry.location);
marker.setMap(map);
// get the location values for the info bubble
if (locPlace.address_components) {
//console.log(locPlace.address_components);
// Populate values for info bubble
locName = locPlace.name;
locIcon = locPlace.icon;
locAddress = locPlace.formatted_address;
locPhone = locPlace.formatted_phone_number;
locWeb = locPlace.website;
}
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn);
infowindow.setContent(infowindowPlace);
infowindow.open(map, marker);
});
}

Projections and OpenLayers.Geometry.Point in openlayers

I'm trying to show a map with three layers (google maps layers, wms layer and points layer) this is my code:
var map = new OpenLayers.Map({
div: "map",
maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
});
var capaGoogle = new OpenLayers.Layer.Google(
"Google Satellite",
{ type: G_SATELLITE_MAP, sphericalMercator: true, transparent: true }
);
var wmsOverlay = new OpenLayers.Layer.WMS("OpenLayers WMS",
"http://localhost:1979/geoserver/wms",
{ layers: 'world:PYCIUDADES', transparent: true }, { isBaseLayer: false });
var vectorLayer = new OpenLayers.Layer.Vector("vector");
vectorLayer.addFeatures([
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-57.635021, -25.276987)
),
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-56.759034, -22.71539)
)
]
);
map.addLayers([wmsOverlay, vectorLayer, capaGoogle]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
var center = new OpenLayers.LonLat(-57.58, -25.27).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
)
map.setCenter(center, 6);
the "vectorLayer" layer must be above of my map, but I get this (my wms layer is in south america, my points have to be also in south america, but they're near africa):
http://i45.tinypic.com/34y40zk.png
What can I do?
Thanks in advance
You should to transform your point's coordinates:
var epsg4326 = new OpenLayers.Projection('EPSG:4326');
var epsg900913 = new OpenLayers.Projection('EPSG:900913');
vectorLayer.addFeatures([
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-57.635021, -25.276987).transform(epsg4326, epsg900913)
),
new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-56.759034, -22.71539).transform(epsg4326, epsg900913)
)
]);
"next to Africa" = longitude 0 latitude 0
when you simply enter Longitude and Latitude, OL considers this a WGS84 projection (standard).
but since you are using a Google layer (CapaGoogle), which is a mercator-referenced projection, you end up using two reference projections (4326 = WGS84 AND 900913 = mercator) simultaneously and the map server disconsiders the location of your markers, since they are "incorrect". therefore, it simply places them at (0,0).
as DrNextGIS said, you must "transform your points coordinates" so that everything on your map uses the same projection.
you would NOT have this problem if you were using a simple OpenLayer map (without Google or OSM).

Categories

Resources