Use iPhone location to update google map - html

I am building a cycle information site and want to be able to grab the users location from their iPhone so i update my Google map and provide the user with relevant information. There is a Drupal module called Geolocation which uses the HTML5 option to do this and i have found the code which it is performing the task in the module below.
// START: Autodetect clientlocation.
// First use browser geolocation
if (navigator.geolocation) {
browserSupportFlag = true;
$('#geolocation-help-' + i + ':not(.geolocation-processed)').addClass('geolocation-processed').append(Drupal.t(', or use your browser geolocation system by clicking this link') +': <span id="geolocation-client-location-' + i + '" class="geolocation-client-location">' + Drupal.t('My Location') + '</span>');
// Set current user location, if available
$('#geolocation-client-location-' + i + ':not(.geolocation-processed)').addClass('geolocation-processed').click(function() {
navigator.geolocation.getCurrentPosition(function(position) {
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
Drupal.Geolocation.maps[i].setCenter(latLng);
Drupal.Geolocation.setMapMarker(latLng, i);
Drupal.Geolocation.codeLatLng(latLng, i, 'geocoder');
}, function() {
Drupal.Geolocation.handleNoGeolocation(browserSupportFlag, i);
});
});
}
Does anybody have any Google Maps API V3 experience of implementing this or similar? I would prefer the user to have to click "My Location" or equivalent to then use their iPhone's location to update the map rather than request it automatically. This is my Map and the array of markers that i have on it. How can i utilise the iPhones location to update it?
function initialize() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(51.51251523, -0.133201961),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
setMarkers(map, spots);
}
var spots = [
['Marylebone', 51.51811784, -0.144228881, '2.png', 2901, 'Broadcasting House - Marylebone</br>Available Bikes: 1</br>Number of Docks: 13</br> View more information about this dock'],
['Fitzrovia', 51.51991453, -0.136039674, '3.png', 2908, 'Scala Street - Fitzrovia</br>Available Bikes: 8</br>Number of Docks: 21</br> View more information about this dock'],
['Fitzrovia', 51.52351808, -0.143613641, '3.png', 2923, 'Bolsover Street - Fitzrovia</br>Available Bikes: 6</br>Number of Docks: 19</br> View more information about this dock'],
['Fitzrovia', 51.52025302, -0.141327271, '3.png', 2975, 'Great Titchfield Street - Fitzrovia</br>Available Bikes: 5</br>Number of Docks: 19</br> View more information about this dock'],
['Bloomsbury', 51.51858757, -0.132053392, '3.png', 2982, 'Bayley Street - Bloomsbury</br>Available Bikes: 12</br>Number of Docks: 25</br> View more information about this dock']
];
function setMarkers(map, locations) {
var image1 = new google.maps.MarkerImage('amber-spot.png',
new google.maps.Size(30, 36),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var spot = locations[i];
var myLatLng = new google.maps.LatLng(spot[1], spot[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: spot[3],
title: spot[0],
zIndex: spot[4],
html: spot[5]
});
bounds.extend(myLatLng);
map.fitBounds(bounds);
var infowindow = new google.maps.InfoWindow({
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.html);
infowindow.open(map,this);
});
}
}
thanks
Lee

First you will need a javascript function that will be fired from a button press, or a link click. This function will use the geolocation api available through html5 to check if the user can provide you with their location and grab it if so. The remainder of the function will use the google maps api to pan to that lat lng coordinate and set the zoom level appropriately.
Here is the google maps api map object which has the methods you need:
http://code.google.com/apis/maps/documentation/javascript/reference.html#Map
And this site has a great overview of basically everything you are trying to do:
http://www.html5laboratory.com/geolocation.php
Finally don't forget to save the location in your database or client side javascript array. If you are saving the data, warn the user of that for privacy implications.

Related

google maps api findplace request not working properly

I want to display on my webpage the location from a JSON that has displayed a pharmacy name. The point is that google maps API is a little bit over my power of knowledge. I did a find-place request into the google maps API, but the location that is displayed is the one from my current location.
Here is the part of the code that would interest you
<div id="map"></div>
<script src="./keys.js"></script>
<script>
let map;
document.addEventListener("DOMContentLoaded", () => {
let s = document.createElement("script");
document.head.appendChild(s);
s.addEventListener("load", () =>
{
console.log("script has loaded");
x = navigator.geolocation;
x.getCurrentPosition(success, failure)
function success(position){
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
var coords = new google.maps.LatLng(myLat,myLong);
map = new google.maps.Map(document.getElementById("map"), {
center: coords,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: coords,
})
}
function failure(){}
});
s.src = `https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=<%= "#{#medicament['farmacies'].first['name']}"%>&inputtype=textquery&fields=formatted_address,name,rating,opening_hours,geometry&key=**************`;
});
</script>
</div>
where <%= "#{#medicament['farmacies'].first['name']}"%> represents the name of the pharmacy from the html erb file.
What I found strange is that if I inspect the page where the location is the s.src takes me to a JSON that has all the right address information for the pharmacy.
Here you can see an image with the response from the API:
What I want is to point to the address of that pharmacy on google map. Any tips&tricks are very welcome!
Use google.maps.places.PlacesService.findPlaceFromQueryinstead.
Also see this tutorial.
var service = new google.maps.places.PlacesService();
var request = {
query: 'Museum of Contemporary Art Australia',
fields: ['name', 'geometry'],
};
const {results} = service.findPlaceFromQuery(request);

Google Map Issue - Ionic 2

Google map shows in the browser but when I run command
ionic run android
it build successfully and launch the app but everything works fine except Google map there are no errors in chrome://inspect it just says DEVICE READY FIRED AFTER 630 ms but no error for google map. I did register app on console.developers.google.com got the key and using it in www/index.html in the head but still no changes. Please help thank you.
home.ts (Map function is inside of this file)
// Get the current location
Geolocation.getCurrentPosition().then((position) => {
// Set latitude and longtitude variable
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
// This function will get the name of the city where user is located
this.getCityName(this.lat, this.long);
// this function sets up the google map
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var mapi = new google.maps.Map(this.mapDiv.nativeElement, mapOptions);
// Below code is provided by a ai pollution control website (http://aqicn.org/faq/2015-09-18/map-web-service-real-time-air-quality-tile-api/)
// haven't changed anything in below code copied as it is from web
var waqiMapOverlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return 'http://tiles.aqicn.org/tiles/usepa-aqi/' + zoom + "/" + coord.x + "/" + coord.y + ".png?token=_TOKEN_ID_";
},
name: "Air Quality",
});
// Insert above received data into map
mapi.overlayMapTypes.insertAt(0,waqiMapOverlay);
`
Probably your map is not getting coordinates(position.coords.latitude, position.coords.longitude) , that's why your map is not rendering. try with navigator.Geoloaction.getCurrentPosition... or check if any plugin is required to get user geolocation. & prefer to give some fallback coordinates.
this.lat = position.coords.latitude || "21.1610858";
this.long = position.coords.longitude || "79.0725101";

Custom Search box for Google map

I am developing web application using Google map JavaScript version. I need to add search box like Google Search box which is on Google map (like attached image). And I need to search custom places which are on my database.
If it is possible, how to do this?
This example adds a search box to a map, using the Google Place Autocomplete feature. People can enter geographical searches. The search box will return a pick list containing a mix of places and predicted search terms.
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Moving object display on google maps or bing

I want to develop an application for tracking in maps,in that i want to show moving object without reloading the whole page depending on co ordinates. Can anyone suggest me how to do so?
Where is the information about moving objects?
Is it a real time system or only a simulation?
In any case you can try polling server to get the new coordinates few times per second using JS, and update marker location on the map.
EDIT
Below you have working example of moving object without polling taken from google tutorial (https://google-developers.appspot.com/maps/documentation/javascript/examples/full/overlay-symbol-animate). What you need to change is the way of obtaining coordinates.
var line;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(20.291, 153.027),
zoom: 6,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var lineCoordinates = [
new google.maps.LatLng(22.291, 153.027),
new google.maps.LatLng(18.291, 153.027)
];
var lineSymbol = {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
strokeColor: '#393'
};
line = new google.maps.Polyline({
path: lineCoordinates,
icons: [{
icon: lineSymbol,
offset: '100%'
}],
map: map
});
animateCircle();
}
function animateCircle() {
var count = 0;
window.setInterval(function() {
count = (count + 1) % 200;
var icons = line.get('icons');
icons[0].offset = (count / 2) + '%';
line.set('icons', icons);
}, 20);
}
google.maps.event.addDomListener(window, 'load', initialize);

Google Map API V3: MarkerClusterer won't break down into markers

I have an application where I'm using the Google Map API to display markers for posts made by users using their lat/lon. I employed the MarkerClusterer capability for better organization of the markers, which works but with a bug of sorts.
Essentially, I've been testing this at home so the lat/lon has been the same for all test posts. Before using MarkerClusterer, zooming far into the map would eventually reveal all the markers. Unfortunately, using the MarkerClusterer, if there is, for example, a "5" listed for the number of markers that are very close together such as these test posts, clicking on the cluster reveals nothing. No markers ever appear when these are very close together. To reiterate, these markers do appear without the MarkerClusterer.
I upgraded to MarkerClustererPlus v2.0.9 per another post that described other issues with the MarkerClusterer but that hasn't solved the problem.
Any insight into this issue would be greatly appreciated.
Edit: geocodezip suggested the overlappingmarkerspidifier, which sounds great, but my code is fairly involved and I'm not sure how to incorporate it. Any insight much appreciated. Code follows:
function mainGeo()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition( mainMap, error, {maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
}
else
{
alert("Sorry, but it looks like your browser does not support geolocation.");
}
}
var stories = {{storyJson|safe}};
var geocoder;
var map;
var markers = [];
function loadMarkers(stories){
for (i=0;i<stories.length;i++) {
var story = stories[i];
if (story.copy.length > 120) {
story.copy = story.copy.substring(0, 120) + "...";
}
(function(story) {
var pinColor = "69f2ff";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=S|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var point = new google.maps.LatLng(story.latitude, story.longitude);
var marker = new google.maps.Marker({position: point, map: map, icon: pinImage});
var infowindow = new google.maps.InfoWindow({
content: '<div >'+
'<div >'+
'</div>'+
'<h2 class="firstHeading">'+story.headline+'</h2>'+
'<div>'+
'<span>'+story.author+'</span><br />'+
'<span>'+story.city+'</span><br />'+
'<span>'+story.topic+'</span><br />'+
'<p>'+story.date+'</p>'+
'<p>'+story.copy+'</p>'+
'<p><a href='+story.url+'>Click to read story</a></p>'+
'</div>'+
'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,this);
});
markers.push(marker);
})(story);
}
}
function mainMap(position)
{
geocoder = new google.maps.Geocoder();
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var width = window.innerWidth - 80;
size = width;
// Prepare the map options
var mapOptions =
{
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
loadMarkers(stories);
var markerCluster = new MarkerClusterer(map, markers);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function error() {
alert("You have refused to display your location. You will not be able to submit stories.");
}
mainGeo();
Perhaps this post in the v3 group: Overlapping markers on your Google Map? Meet OverlappingMarkerSpiderfier might help:
Sounds like the OverlapingMarkerSpiderifier solves your problem.