Google maps api and geolocation, Javascript and Html - javascript

Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
var map;
var infowindow;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
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
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Working code
var map;
var infowindow;
function initialize() {
var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
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
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Any help if appreciated :)

Replace your line:
var latlon = new google.maps.LatLng
(position.coords.latitude + "," + position.coords.longitude);
with
var latlon = new google.maps.LatLng
(position.coords.latitude, position.coords.longitude);
The problem is in concatenating two values into one where constructor expects two parameters.

Related

Autocompletion en show on map

I have tried to make autocompletion for my application and show this to my Google maps but it doesn't works well.
The code is in a seperate js file called autocomplete.js
I already have a google maps in app so I want to use the same.
The id of google map is: googleMap
The id of search button is: autosearch
The id of input is: autoinput
"use strict";
var input = document.getElementById('autoinput');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
var input = document.getElementById('autoinput');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'be'}
};
function fillInAddress() {
var place = autocomplete.getPlace();
var defaultBounds = document.getElementById('googleMap')(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('autoinput');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
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)
};
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
};
I changed code etc but i guess i deleted something that i need.
This is the other js file for geolocation called locationSearch.js:
var google;
$( document ).ready(function() {
zoekLocatie();
});
function zoekLocatie() {
var output = document.getElementById("googleMap");
navigator.geolocation.getCurrentPosition(success, error);
output.innerHTML = "<p>Looking for your location...</p>";
if (!navigator.geolocation) {
output.innerHTML = "<p>Your browser doesn't support geolocation</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var mapProp = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 18,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow);
function geocodeLatLng(geocoder, map, infowindow) {
var input = latitude + "," + longitude;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(18);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
address.innerHTML = results[1].formatted_address;
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
you have a error here
use strict";
you should remove the "
And where you call your google map function ?

Google Maps API with Geolocation and Places Search

I'm using the Google Maps and places API. I'm trying to have the map show current location WITH surrounding restaurants, cafes, and bars. At this point the map loads and the geolocation is working. I can't seem to get the place markers to show up. I have no idea what I'm missing as I'm learning javascript as quickly as possible.
Any help would be very much appreciated. Thank You!
Here is my current code:
<script>
var map;
var service;
var marker;
var pos;
var infowindow;
function initialize()
{
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
panControl: false,
streetViewControl: false,
mapTypeControl: false,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//HTML5 geolocation
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
infowindow = new google.maps.InfoWindow({map: map,position: pos,content: 'You Are Here'});
var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};
map.setCenter(pos);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
},
function()
{
handleNoGeolocation(true);
});
}
else
{
handleNoGeolocation(false);
}
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
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Check that your script call to the Google API includes a reference to the places library. For example:
<script src="http://maps.googleapis.com/maps/api/js?key=yourAPIkey&libraries=geometry,places&sensor=true&language=en"></script>
In this line of code:
var request = {location:pos,radius:500,types: ['restaurant, cafe, bars']};
instead of types: write keyword:

Google maps how to search for places with button click

i got this code but it appears when the map load, i need that by clicking in a button to hide and show the search result, can an1 help please ?
code:
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
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
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);\
EDIT
I trying to create a button that when clicked shows the search result of google places .. I hid the maker and made a function to the button show the marker, but this is not working out
function createMarker(place) {
var placeLoc = place.geometry.location;
var markersr = new google.maps.Marker({
map: map,
icon:icon2,
visible:false,
position: place.geometry.location,
});
function
function showsearch() {
markersr.setVisible(true);
}
button
<input type="checkbox" name="btn2" onClick="showsearch()" class="btn2" >
Please refer the link. http://jsfiddle.net/y829C/1/
var mapOptions = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Update:
Refer the link:http://jsfiddle.net/y829C/11/

Google maps zoom level for country

I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example

Geolocation with PlacesServices

What i am trying to do is find my current location with the Geolocation API, and then add the google places, to show what is around myself. However what I have so far only returns a specific location...
<script>
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
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
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
As you can see pyrmont - gives me the lat and long, but i would like to replace with this the users current location. So I can find out where they are and then give them some shops. I keep drawing a blank when I try to do this. I have done geolocation before with:
new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
however if I use this var in the lat long section I get a loverly error. Thanks for any help in advance.
Okay this did it:
<script>
var map;
      function initialize() {
        var mapOptions = {
          
        };
        map = new google.maps.Map(document.getElementById('contact-map'),{
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP   
        });
        // Try HTML5 geolocation
        if(navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);
            var request = {
          location: pos,
          radius: 500,
          types: ['store']
        };
            
            var marker = new google.maps.MarkerImage('../img/layout/marker.png');
            
            var infowindow = new google.maps.InfoWindow({
              map: map,
              position: pos,
              icon: marker,
              content: 'youre here'
            });
            var service = new google.maps.places.PlacesService(map);
            service.nearbySearch(request, callback);            
            
            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
        });
      google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(place.name);
      infowindow.open(map, this);
  });
  }
            
            map.setCenter(pos);
          }, function() {
            handleNoGeolocation(true);
          });
        } else {
          // Browser doesn't support Geolocation
          handleNoGeolocation(false);
        }
      }
      function handleNoGeolocation(errorFlag) {
        if (errorFlag) {
          var content = 'Error: The Geolocation service failed.';
        } else {
          var content = 'Error: Your browser doesn\'t support geolocation.';
        }
        var options = {
          map: map,
          position: new google.maps.LatLng(60, 105),
          content: content
        };
        var infowindow = new google.maps.InfoWindow(options);
        map.setCenter(options.position);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
</script>

Categories

Resources