Google maps get position of an marker - google-maps

I am adding multiple markers, and what I want to do is on click, get that specific marker position.
However at the moment it does work however it displays lat and lng for the last marker created. How can this be solved so that when I click on the marker it will give me that specific position of that marker.
function algolia_search(position) {
clearOverlays();
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'businesses';
var PARAMS = { hitsPerPage: 20 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
markers.push(marker);
marker.addListener('click', function() {
var destinationLat = marker.getPosition().lat();
var destinationLng = marker.getPosition().lng();
console.log(lat);
console.log(lng);
console.log(destinationLat);
console.log(destinationLng);

you need a listerner on map for click in event.latLng you have coordinates
google.maps.event.addListener(map, 'click', function(event) {
alert ( 'Lat : ' + event.latLng.lat() + ' Lng : ' + event.latLng.lng())
});
do the fact you have already place the marker on maps you could use a closure
var addListenerOnPoint = function(actMark){
actMark.addListener('click', function() {
alert ( 'Lat : ' + actMark.position.lat() + ' Lng : ' +actMark.position.lng());
});
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
addListenerOnPoint(marker,
);
markers.push(marker);
}

Related

How to get coordinates in polyline using google map?

I tried to create a polyline in google Maps. It's created and polyline also working fine. but I need when to click polyline to get coordinates. My Scenario(I have three markers in google map.so, three markers used to connect the polyline markerA connect to markerB connect to markerC. when I click polyline in between markerA and makrerB. I need that two markers latitude and longitude). How to achieve this scenario.
My Code
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var goldenGatePosition = [{lat: 11.0168,lng: 76.9558},{lat: 11.6643,lng: 78.1460},{lat:11.2189,lng:78.1674}];
for(let i=0;i<goldenGatePosition.length;i++){
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
}
var flightPath = new google.maps.Polyline({
path:goldenGatePosition,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(map);
var infowindow = new google.maps.InfoWindow();
var codeStr=''
google.maps.event.addListener(flightPath, 'click', function(event) {
infowindow.setContent("content");
// var pathArr = flightPath.getPath()
// for (var i = 0; i < pathArr.length; i++){
// codeStr = '{lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
// console.log(codeStr)
// };
console.log(event.latLng)
var length = this.getLength();
var mid = Math.round( length / 2 );
var pos = this.getAt( mid );
console.log(pos)
// infowindow.position = event.latLng;
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCHmYOxkvd4u3rbHqalUSlGOa-b173lygA&callback=myMap"></script>
</body>
</html>
Google Map
Simplest way:
include the google maps geometry library.
use the poly namespace isLocationOnEdge method to detect which segment of the polyline the click was on. Output the two end coordinates of that segment.
isLocationOnEdge(point, poly[, tolerance])
Parameters:
point: LatLng
poly: Polygon|Polyline
tolerance: number optional
Return Value: boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline,10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment "+i+"<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
proof of concept fiddle
code snippet:
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#googleMap {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<h1>My First Google Map</h1>
<div id="googleMap"></div>
<script>
function myMap() {
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var goldenGatePosition = [{
lat: 11.0168,
lng: 76.9558
}, {
lat: 11.6643,
lng: 78.1460
}, {
lat: 11.2189,
lng: 78.1674
}];
var bounds = new google.maps.LatLngBounds();
for (let i = 0; i < goldenGatePosition.length; i++) {
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
bounds.extend(goldenGatePosition[i]);
}
var flightPath = new google.maps.Polyline({
path: goldenGatePosition,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2
});
flightPath.setMap(map);
map.fitBounds(bounds);
var infowindow = new google.maps.InfoWindow();
var codeStr = ''
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment " + i + "<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap"></script>

Algolia search, displaying all results even when radius set

So I want to search by lat and lng within 5km radius, despite limiting hits per page to 10, it is still displaying all markers on map and there are 96, why isn't this working properly?
var APPLICATION_ID = '**';
var SEARCH_ONLY_API_KEY = '**';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 10 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
algoliaHelper.setQueryParameter('aroundLatLng', '53.552472, -2.807663');
algoliaHelper.setQueryParameter('aroundRadius', 5000);
algoliaHelper.search();
// Map initialization
var markers = [];
//alert("heelo");
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
label: hit.slug,
animation: google.maps.Animation.DROP
});
markers.push(marker);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
});
How a very weird reason if I delete:
algoliaHelper.setQueryParameter('aroundLatLng', '53.552472, -2.807663');
algoliaHelper.setQueryParameter('aroundRadius', 5000);
algoliaHelper.search();
It still brings back all records, does anyone have a clue why is this happening?

Algolia and google filter results based on user position

Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}

How to update coordinates of marker?

I use Google Maps API and add the markers on the map:
for(var i = 1; i <= 100; i++){
var position = {lat : i, lng : i};
var marker = new google.maps.Marker({
position: position,
map: map,
draggable: true
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
How I can update coordinates for marker[i] = 22 if this marker was created before?
Pusth the markers in an array and use setPosition
var markers;
var k;
for(var i = 1; i <= 100; i++){
var position = {lat : i, lng : i};
var marker = new google.maps.Marker({
position: position,
map: map,
draggable: true
});
k = markers.push(marker);
markers[k-1].addListener('click', function() {
infowindow.open(map, this);
});
}
.....
var myNewlatlng = new google.maps.LatLng( 24.397, 40.644);
markers[22] setPosition(myNewlatlng);

Google Maps API v3 Point of Interest with Custom Icons

I have a page pulling in the schools, churches, and parks of my given area but I want to style the 3 POIs with 3 different icons. I searched Google and even all the docs but couldn't find the answer.
var map;
var infowindow;
function initialize() {
// Center of Map
var centerLatlng = new google.maps.LatLng(29.745376, -95.380125);
// Marker Icons Declaration
var icon = new google.maps.MarkerImage("smLinks-twitter.png", null, null, new google.maps.Point(41,47));
// Map Options
var myOptions = {
zoom: 16,
center: centerLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
icons: icon
};
// Draw the map
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Marker Icons Implementation
markers = new google.maps.Marker({
position: centerLatlng,
map: map,
title: 'Center of Map',
icon: icon
});
// Services: Places
var request = {
location: centerLatlng,
radius: 800,
types: ["school", "church", "park"]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
} // function initialize()
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,
icon: icon
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name + '<br/>' + place.vicinity + '<br/><img src="' + place.icon + '">');
infowindow.open(map, this);
});
}
Please see my quick and dirty Demo. The idea is to use the place.types array to determine what kind of place you are trying to add to the map. I simplistically assigned a marker to the first item of this array (usually 2 or 3 items long), which may be something like:
["school", "establishment"]
In some cases, "university" comes before "school" so a "university" icon is used. You will want to refine the way you match types to icons, that is, give a priority for school or university? Perhaps iterate through the array looking for the right types. One place (general_contractor) is not in my list of icons, so the default pin marker is placed there. A "default" icon could be used if you checked if iconType in fact has or not the desired type. I'll leave these details to you =)
Here's the source I used for icons: https://sites.google.com/site/gmapsdevelopment/
function createMarker(place) {
var placeLoc = place.geometry.location;
var iconType = {};
iconType['school'] = "http://maps.google.com/mapfiles/kml/pal2/icon2.png";
iconType['church'] = "http://maps.google.com/mapfiles/kml/pal2/icon11.png";
iconType['park'] = "http://maps.google.com/mapfiles/kml/pal2/icon12.png";
iconType['university'] = "http://maps.google.com/mapfiles/kml/pal2/icon14.png";
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: iconType[place.types[0]]
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name + '<br/>' + place.vicinity + '<br/><img src="' + place.icon + '">');
infowindow.open(map, this);
});
}
Alternatively, use a switch statement:
function createMarker(place) {
var placeLoc = place.geometry.location;
var iconUrl;
switch (place.types[0]) {
case 'school':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon2.png";
break;
case 'church':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon11.png";
break;
case 'park':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon12.png";
break;
case 'university':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon14.png";
break;
default:
iconUrl = "http://maps.google.com/mapfiles/kml/pal4/icon39.png";
}
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: iconUrl
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name + '<br/>' + place.vicinity + '<br/><img src="' + place.icon + '">');
infowindow.open(map, this);
});
}