Find the midpoint of several locations using google map [duplicate] - ruby-on-rails

This question already has answers here:
Find center of multiple locations in Google Maps
(4 answers)
Closed 8 years ago.
I've wrote a code for my Rails app to show some locations on the google map using the following code:
var myOptions = {
zoom: 2,
center: new google.maps.LatLng(71.1333,27.7000, 13), // **I need to set the center from the locations in here.**
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#search_map_canvas')[0], myOptions);
var addresses = <%=raw search_offering_addressess.to_json %>;
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
Here, search_offering_addressess contains an array of locations. E.g. ["Berlin, germany", "zurich, switzerland", ....]
How can I find the midpoint of that locations? My map misses some locations marker.

try this using LatLngBounds
//newly added
var bounds = new google.maps.LatLngBounds();
var myOptions = {
zoom: 2,
center: new google.maps.LatLng(71.1333,27.7000, 13), // **I need to set the center from the locations in here.**
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#search_map_canvas')[0], myOptions);
var addresses = <%=raw search_offering_addressess.to_json %>;
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//newly added
bounds.extend(latlng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);

Related

Draw a circle again after vector export

After draw a circle in my map, I exported it with:
getAsJson : function() {
var geojson = new ol.format.GeoJSON();
var features = this.vectorSource.getFeatures();
var jsonData = geojson.writeFeatures( features,{
featureProjection: ol.proj.get('EPSG:3857'),
dataProjection: ol.proj.get('EPSG:4326')
});
return jsonData;
}
and the result was:
{"type":"FeatureCollection","features":[
{"type":"Feature","geometry":{
"type":"GeometryCollection","geometries":[]
},"properties":{
"circleCenter":[-4805776.093508227,-2600749.7153150304],"circleRadius":6658.801529937424
}
}]}
This is how I take the circle center and radius:
var draw = new ol.interaction.Draw({
source: vectorSource,
type: value, // Can be Circle,Point,Line,Polygon
// No Geometry Function when type is 'Circle' (omited code to simplify)
geometryFunction: geometryFunction,
maxPoints: maxPoints
});
draw.on('drawend', function( evt ){
var geometry = evt.feature.getGeometry();
// Check the type before try to get this! (omited code to simplify)
var center = geometry.getCenter();
var radius = geometry.getRadius();
evt.feature.set('circleCenter', center );
evt.feature.set('circleRadius', radius );
});
map.addInteraction( draw );
Now I'm trying to use this JSON to draw the same circle again, but it have no geometry and this is not working (work for all other geometries like point, polygong and line so the problem is it not the code):
var features = new ol.format.GeoJSON().readFeatures( jsonData, {
featureProjection: 'EPSG:3857'
});
var vectorSource = new ol.source.Vector({
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style : customStyleFunction
});
map.addLayer( vectorLayer );
Just a note: I can see now the projection of center and radius was not changed. Must work on this too...
GeoJSON does not support Circle Geometry. So ol.format.GeoJSON() format doesnot convert JSON to ol.Feature object. So write a custom method which consumes the JSON data and creates a Circle geometry
var featuresJson = geoJson.features;
for ( var i=0; i<featuresJson.length; i++ ) {
var radius = featuresJson[i].properties.circleRadius;
var center = featuresJson[i].properties.circleCenter;
var feature = new ol.Feature(new ol.geom.Circle(center,radius);
vectorSource.addFeature(feature);
}
I think this can help me somehow... will see.
map.getViewport().addEventListener("dblclick", function(e) {
var coordinate = map.getEventCoordinate(e);
vectorSource.addFeature(new ol.Feature(new ol.geom.Circle(coordinate, dist)));
});

URL parameters for Openlayers 3 to zoom to location?

I have an OL3 web application and I am wondering if it is possible to include URL parameters (such as coordinate values) for which the application can parse and open up at a specific location?
For example http://mywebsiteaddress?x=longitudevalue&y=latitudevalue
Is this something that can be done using OL3?
Sure, see: http://openlayers.org/en/latest/examples/permalink.html for an example (uses an anchor instead of url parameters but the idea is the same).
I did not like the openlayers permalink example because it uses map units and not well-known latitudes and longitudes. Sp I wrote my own code to hand over latlon coordinates, zoom and set a marker to it:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var mzoom=12;
var mlat = Number(getURLParameter('mlat'));
var mlon = Number(getURLParameter('mlon'));
var mzoom = Number(getURLParameter('zoom'));
var marker = 1
if (mlat == 0 || mlon == 0) {
mlat = 51.5; mlon = 7.0; mzoom=12; marker=0 //Default location
}
if (mzoom == 0 ) { mzoom=12 //Default zoom
}
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
closer.onclick = function() {
container.style.display = 'none';
closer.blur();
return false;
};
var overlayPopup = new ol.Overlay({
element: container
});
var expandedAttribution = new ol.control.Attribution({
collapsible: false
});
var map = new ol.Map({
controls: ol.control.defaults({attribution:false}).extend([
expandedAttribution
]),
target: document.getElementById('map'),
renderer: 'canvas',
overlays: [overlayPopup],
layers: layersList,
view: new ol.View({
center: ol.proj.fromLonLat([mlon, mlat]),
zoom: mzoom,
maxZoom: 18, minZoom: 8
})
});
if (marker == 1) {
var vectorLayer = new ol.layer.Vector({
source:new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([parseFloat(mlon), parseFloat(mlat)], 'EPSG:4326', 'EPSG:3857')),
})]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "marker.svg"
})
})
});
map.addLayer(vectorLayer);
}
I used the output of the qgis2web plugin and modified the file qgis2web.js as above.

i want to develop a dynamic url lake google max , when i send ajax request?

in search/index.html
<div id="map"></div>
in search.js
var lat = 17.0123;
var lng = 28.0124538;
var position = new google.maps.LatLng(lat,lng);
var zoomLevel = 8;
var mapId = document.getElementById('map');
var map;
function initMap(){
map = new google.maps.Map(mapId, {
center: position,
zoom: zoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
google.maps.event.addListener(map, 'idle', function() {
var map_centre = map.getCenter();
lat = map_centre.lat();
lng = map_centre.lng();
}
});//idel function end
Now i want to get the dynamic url of zoom level and latitude and langitude of map using turbo links in my rails project.
Can you help me how to do?

automatic geolocation in ruby

I jus started learn ruby on rails and currently I am creating my first rails app. And I ran into some problems. In my app, I would like to get user's position (latitude, longitude). So I can put the button "find me" and return user's locations. But I would like to load my page and show my position (latitude, longitude), don't press any buttons. And then use lat and lng in my controllers. How can I do this?
Add the below script in your view page.You may go ahead and modify this as needed as to show/customise messages and buttons.Remember to have a dedicated div with id="map-canvas" to show you map on the page.
I have used geocomplete.js to show map and allow user to enter places from search box .You may remove the scripts using geocomplete if not needed.
<script type="text/javascript">
// Enable the visual refresh
// google.maps.visualRefresh = true;
var map;
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: '<p>You are here!</p>'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}//initialize ends
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = '<p>Unable to find the current location</p>';
} else {
var content = '<p Your browser doesn\'t support geolocation.</p>';
}
var options = {
map: map,
zoom: 5,
position: new google.maps.LatLng(60, 105),
content: content
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(60, 105),
map: map,
animation: google.maps.Animation.DROP,
title: 'Sorry,we were unable to find your location'
});
marker.setAnimation(google.maps.Animation.BOUNCE);
var infowindow = new google.maps.InfoWindow(options);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
infowindow.open(map,marker);
map.setCenter(options.position);
}//handleNoGeolocation ends
//load the page and execute above scripts
$(document).ready(function(){
$('#map-canvas').html("<p class='text-center text-alert'>Loading map...</p>").show(3000);
//load the map after 2 seconds
setTimeout('initialize()', 3000);
// $("#geocomplete").geocomplete({
// map: ".map-canvas-guest"
// });
//you may use this or remove this section using geocomplete.js if not needed.
$("#geocomplete").geocomplete();
$("#geocomplete").geocomplete(mapOptions).bind("geocode:result", function(event, result){
console.log(result.formatted_address);
//use this user entered address and you may call ajax here as well
})
})//document ends
</script>

how to get these Lat/Long from zip code to draw boundary of that zip code area

Following is the code to draw boundaries on google map using collection of Lat and Lnt.
var map;
var markersList = [
new google.maps.LatLng(50.835866, 4.258575),
new google.maps.LatLng(50.818083, 4.244499),
new google.maps.LatLng(50.811358, 4.276428),
new google.maps.LatLng(50.813094, 4.302177),
new google.maps.LatLng(50.773162, 4.338226),
new google.maps.LatLng(50.764259, 4.384918),
new google.maps.LatLng(50.793132, 4.482422),
new google.maps.LatLng(50.810274, 4.450836),
new google.maps.LatLng(50.821120, 4.476585),
new google.maps.LatLng(50.852342, 4.462852),
new google.maps.LatLng(50.866861, 4.421310),
new google.maps.LatLng(50.895021, 4.430580),
new google.maps.LatLng(50.911692, 4.413757),
new google.maps.LatLng(50.912342, 4.395561),
new google.maps.LatLng(50.898486, 4.377708),
new google.maps.LatLng(50.900868, 4.328957),
new google.maps.LatLng(50.889174, 4.293251),
new google.maps.LatLng(50.880294, 4.297028),
new google.maps.LatLng(50.861878, 4.279175),
new google.maps.LatLng(50.855593, 4.288788),
new google.maps.LatLng(50.837817, 4.282608),
new google.maps.LatLng(50.835866, 4.259605)
];
$(document).ready(function () {
var latlng = new google.maps.LatLng(50.834999, 4.387665);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var MarkerHightlight;
//DRAW THE POLYGON OR POLYLINE
MarkerHightlight = new google.maps.Polygon({
paths: markersList,
strokeColor: "#6666FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#6666FF",
fillOpacity: 0.0
});
MarkerHightlight.setMap(map);
But, I want to draw boundary on google map using zip code (like boundary of mumbai). So, how to get the collection lat/lng for boundaries using zip code of area.

Resources