Autocompletion en show on map - javascript

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 ?

Related

Uncaught TypeError: Cannot read properties of undefined (reading '$wire') at Livewire.value (VM951 livewire.js:13:145634)

I have error with google map when it put Marker it get this error
I do not know what the error is when I click on save it outputs that the data is field is required. in the map it selects the place but when I click on the place this error comes out at the bottom
VM951 livewire.js:13 Uncaught TypeError: Cannot read properties of undefined (reading '$wire')
at Livewire.value (VM951 livewire.js:13:145634)
at placeMarkerAndPanTo (make:2811:27)
at make:2792:11
at geocoder.js:6:1385
at geocoder.js:3:420
at bza (geocoder.js:2:218)
at gia.e [as m] (geocoder.js:3:339)
at Object.c [as _yj5gms] (common.js:123:253)
at GeocodeService.Search?5m2&1d24.745676471010597&2d46.7278229712639&9sen-US&callback=_xdc_._yj5gms&key=AIzaSyDy4tKkS30XU9DJsUA5cqLzg-jtynKS18s&token=45746:1:28
I do not know what the error is when I click on save it outputs that the data is field is required. in the map it selects the place but when I click on the place this error comes out at
this is my code
#section('scripts')
<script src="https://maps.googleapis.com/maps/api/js?key={{env("GOOGLE_KEY")}}&libraries=places&v=weekly"> </script>
<script src="{{ asset('dashboard/assets/js/pages/crud/forms/widgets/select2.js') }}"></script>
<script>
$(document).ready(function() {
$('#kt_select2_3').select2({
placeholder: '',
}).on('change', function() {
#this.properties = $(this).val();
});
});
function mapLocation() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var lat, lng;
var markers = [];
var gmarkers = [];
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var riyad = new google.maps.LatLng(24.729518, 46.723341);
var mapOptions = {
zoom: 13,
center: riyad,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
map.addListener('click', function(e) {
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': e.latLng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[1].formatted_address);
if (results[1]) {
//results = results[1];
//var result12 = results[1].formatted_address;
// //document.getElementById("address_pickUp").innerHTML = results[1].formatted_address;
// // alert(document.getElementById("address_pickUp").innerHTML.length)
// if(document.getElementById("address_pickUp").innerHTML.length == 0){
// document.getElementById("address_pickUp").innerHTML = results[1].formatted_address;
// }else{
// document.getElementById("address_dropOff").innerHTML = results[1].formatted_address;
// }
//#this.address = results[1].formatted_address;
// alert("Location: " + results[1].formatted_address + "\r\nLatitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
//alert(result12);
}
}
placeMarkerAndPanTo(e.latLng, map, results[1].formatted_address);
});
});
var marker = new google.maps.Marker({
// position: markers[0],
position: markers,
map: map
});
function placeMarkerAndPanTo(latLng, map, results) {
if (document.getElementById("pickup_lat").value.length == 0) {
document.getElementById("pickup_lat").value = latLng.lat();
document.getElementById("pickup_lng").value = latLng.lng();
document.getElementById("address_pickUp").value = results;
marker.setPosition(latLng);
map.panTo(latLng);
#this.pickup_lat = latLng.lat();
#this.pickup_lng = latLng.lng();
} else {
document.getElementById("dropoff_lat").value = latLng.lat();
document.getElementById("dropoff_lng").value = latLng.lng();
document.getElementById("address_dropOff").value = results;
marker.setPosition(latLng);
map.panTo(latLng);
#this.dropoff_lat = latLng.lat();
#this.dropoff_lng = latLng.lng();
}
}
directionsDisplay.setMap(map);
google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute);
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
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 = [];
// For each place, get the icon, name and location.
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)
};
console.log("latitude: " + place.geometry.location.lat() + ", longitude: " + place.geometry.location.lng());
/*if (document.getElementById("pickup_lat").value.length == 0) {
document.getElementById("pickup_lat").value = place.geometry.location.lat();
document.getElementById("pickup_lng").value = place.geometry.location.lng();
// marker.setPosition(latLng);
// map.panTo(latLng);
//#this.pickup_lat = place.geometry.location.lat();
//#this.pickup_lng = place.geometry.location.lng();
} else {
document.getElementById("dropoff_lat").value = place.geometry.location.lat();
document.getElementById("dropoff_lng").value = place.geometry.location.lng();
}*/
// Create a marker for each place.
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);
});
}
#endsection
make-trip.blade.php
<div class="col-lg-12" wire:ignore>
<div class="col-lg-3">
<x-input type="text" field="map" style="margin: 10px; z-index: 0; position: absolute; cursor: pointer; left: 0px; top: 0px;width:350px" placeholder="Search Box" id="pac-input"></x-input>
</div>
I do no now what is the error

Working with two google maps

Hi I need some help with the following:
I am trying to get two maps to display two different things.
My problem is, on the first map I would like to click on a link in the infowindow (see this) when I do click on that link, I would like that marker to display alone on the second map at its location.
here is my code. Thank you for any help.
$(document).ready(function() {
var map;
var service;
function initialise(location) {
console.log("location:" + location);
var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOption = {
center : currentLocation,
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOption);
var marker = new google.maps.Marker({
position : currentLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
//service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
function handleSearchResults(results, status) {
console.log(results)
}
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
});
var content = '<p>See this</p>'
var infowindow = new google.maps.InfoWindow({
content:('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + content)
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
var latitude = this.position.lat();
var longitude = this.position.lng();
console.log(this.position);
});
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var input = $("#search").val();
var query = (input != '' )? input : "restaurant";
performSearch(query);
});
function performSearch(q){
var request ={
bounds: map.getBounds(),
query:String(q)
};
service.textSearch(request, callback);
}
}
function initializer() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
});
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position : initialLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
}
function initializer_2() {
var mapOption2 = {
center : new google.maps.LatLng(41.923, 12.513),
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
var marker = new google.maps.Marker({
// need the position of marker
//position : currentLocation,
map : map,
});
map = new google.maps.Map(document.getElementById("map-canvas2"), mapOption2);
}
google.maps.event.addDomListener(window, 'load', initializer);
google.maps.event.addDomListener(window, 'load', initializer_2);
$(".getSearch").click(function () {
navigator.geolocation.getCurrentPosition(initialise);
});
});

how to close info window when other info window open in google map javascript

its working fine but i have one problem which is that when i open a info window its opened but when i open other info window. the last one info window still opened. but i want to close it when we open new inf window
<script>
window.onload = getMyLocation;
var geocoder;
var map;
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("Oops, no geolocation support");
}
}
//This function is inokved asynchronously by the HTML5 geolocation API.
function displayLocation(position) {
//The latitude and longitude values obtained from HTML 5 API.
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
//Creating a new object for using latitude and longitude values with Google map.
var latLng = new google.maps.LatLng(latitude, longitude);
showMap(latLng);
addNearByPlaces(latLng);
createMarker(latLng);
//Also setting the latitude and longitude values in another div.
// var div = document.getElementById("location");
//div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
function showMap(latLng) {
geocoder = new google.maps.Geocoder();
var markers = [];
//Setting up the map options like zoom level, map type.
var mapOptions = {
center: latLng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Creating the Map instance and assigning the HTML div element to render it in.
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
// Create the search box and link it to the UI element.
}
function addNearByPlaces(latLng) {
var nearByService = new google.maps.places.PlacesService(map);
var request = {
location: latLng,
radius: 500,
types: ['atm']
};
nearByService.nearbySearch(request, handleNearBySearchResults);
}
function handleNearBySearchResults(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(place.geometry.location, place);
}
}
function createMarker(latLng, placeResult) {
var markerOptions = {
position: latLng,
map: map,
animation: google.maps.Animation.DROP,
clickable: true
}
//Setting up the marker object to mark the location on the map canvas.
var marker = new google.maps.Marker(markerOptions);
if (placeResult) {
var content = "<b>Name : </b>"+placeResult.name+"<br/><b>Address : </b>"+placeResult.vicinity+"<br/><b>Type : </b>"+placeResult.types+"<br/> Rating : "+placeResult.rating+"<br/>" ;
addInfoWindow(marker, latLng, content);
}
else {
var content = "You are here: ";
addInfoWindow(marker, latLng, content);
}
}
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 latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
<!-- alert("Latitude: " + latitude + "\nLongitude: " + longitude); -->
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
var latLngs = new google.maps.LatLng(latitude, longitude);
addNearByPlaces(latLngs);
createMarker(latLngs);
});
}
function addInfoWindow(marker, latLng, content) {
var infoWindowOptions = {
content: content,
position: latLng
};
var infowindow = new google.maps.InfoWindow(infoWindowOptions);
google.maps.event.addListener(marker, 'click', function() {
if(!marker.open){
infowindow.open(map,marker);
marker.open = true;
}
else{
infowindow.close();
marker.open = false;
}
});
}
</script>
I use something like this for closing all infoWindows:
infoWindows = []; //variable to store all infoWindows
function createMarker( map, latlng, title, content, icon ) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon,
title: title
});
var infoWindow = new google.maps.InfoWindow({
content: content
});
infoWindows.push( infoWindow );
google.maps.event.addListener(marker, 'click', function () {
closeAllInfoWindows();
infoWindow.open(map, marker);
});
}
function closeAllInfoWindows() {
for (var i=0;i<infoWindows.length;i++) {
infoWindows[i].close();
}
}

Googlemaps api v3: Markers not showing in Android Browser

Morning,
I have created a mobile web app which plots multiple nearby locations on a Googlemap using API v3.
This works fine in Mobile Chrome, Mobile Firefox & Mobile Opera, but does not work properly in Androids native browser. In the latter, the markers are not shown. It does not give me error messages either.
The URI is
213.175.198.56/~webdesig/restaurants/
Here is the code:
<div id="map1" class="gmap"></div>
<script type="text/javascript">
var map1, latlng1, options1;
var distance = 2000;
function initialize() {
latlng1 = new google.maps.LatLng(localStorage.getItem("lat"), localStorage.getItem("long"));
options1 = { zoom: 12, center: latlng1, mapTypeId: google.maps.MapTypeId.ROADMAP };
//map1 = new google.maps.Map(document.getElementById("map1"), options1);
map1 = new google.maps.Map(document.getElementById('map1'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng1,
zoom: 12
});
var request = {
location: latlng1,
radius: distance,
types: ['restaurant', 'cafe']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map1);
service.nearbySearch(request, callback);
document.getElementById('showing').innerHTML = "Showing restaurants within "+distance+" metres of your location";
}// initialize
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}else{
alert('Unable to plot');
}
}
// Function for adding a marker to the page.
function addMarker(mylocation) {
marker = new google.maps.Marker({
position: mylocation,
map: map1
});
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var request2 = { reference: place.reference };
service.getDetails(request2, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
var rating = details.rating;
if(!rating){rating = 'Not yet rated';}
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />Rating: " +rating + "<br /><input type=\"button\" onclick=\"location.href='tel:" + details.formatted_phone_number+"'\" value=\"Call "+details.name+" \"/>");
infowindow.open(map1, this);
});
});
var image = new google.maps.MarkerImage(
'images/icons/restaurant.png',
new google.maps.Size(32,50),
new google.maps.Point(0,0),
new google.maps.Point(16,50)
);
var shadow = new google.maps.MarkerImage(
'images/icons/restaurantshadow.png',
new google.maps.Size(60,50),
new google.maps.Point(0,0),
new google.maps.Point(16,50)
);
var shape = {
coord: [28,0,29,1,30,2,31,3,31,4,31,5,31,6,31,7,31,8,31,9,31,10,31,11,31,12,31,13,31,14,31,15,31,16,31,17,31,18,31,19,31,20,31,21,31,22,31,23,31,24,31,25,31,26,31,27,31,28,30,29,29,30,28,31,21,32,21,33,20,34,20,35,20,36,20,37,19,38,19,39,19,40,18,41,18,42,18,43,18,44,17,45,17,46,17,47,16,48,16,49,15,49,15,48,15,47,15,46,14,45,14,44,14,43,13,42,13,41,13,40,12,39,12,38,12,37,11,36,11,35,11,34,10,33,10,32,3,31,2,30,1,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,1,2,2,1,3,0,28,0],
type: 'poly'
};
var marker = new google.maps.Marker({
icon: image,
shadow: shadow,
shape: shape,
map: map1,
position: place.geometry.location
});
/*google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name+'<br/>'+place.formatted_address);
infowindow.open(map1, this);
});*/
}
$('.page-map1').live("pagecreate", function() {
initialize();
});
$('.page-map1').live('pageshow',function(){
//console.log("test");
google.maps.event.trigger(map1, 'resize');
map1.setOptions(options1);
// Testing the addMarker function
here = new google.maps.LatLng(localStorage.getItem("lat"), localStorage.getItem("long"));
addMarker(here);
});
</script>

Google maps api and geolocation, Javascript and Html

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.

Categories

Resources