I want to set a marker when I open up my google maps page on my current location.
This marker needs to be changed when I enter an adress in the textfield.
I have no clue how I have to add the standard marker on my location and update it when an adress is entered in the textfield.
I already have the Lat & long of the current position.
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
type="text/javascript"></script>
<style type="text/css">
body {
font-family: sans-serif;
font-size: 14px;
}
#map_canvas {
height: 400px;
width: 600px;
margin-top: 0.6em;
}
</style>
<script type="text/javascript">
var gl;
var ownlat;
var ownlng;
function displayPosition(position)
{
ownlat = position.coords.latitude;
ownlng = position.coords.longitude;
var p = document.getElementById("p");
p.innerHTML = "Own Latitude = " + ownlat + " <br/>" +
"Own Longitude = " + ownlng;
}
function displayError(positionError)
{
alert("error " + positionError.code);
}
try
{
if (typeof navigator.geolocation === 'undefined')
{
gl = google.gears.factory.create('beta.geolocation');
} else {
gl = navigator.geolocation;
}
} catch(e) {}
if (gl)
{
gl.getCurrentPosition(displayPosition, displayError);
} else
{
alert("Geolocation services are not supported by your web browser.");
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
//GET LAT & LONG
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
document.getElementById('lat').innerHTML = lat;
document.getElementById('long').innerHTML = long;
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Related
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
Firstly, I have been checking all over the web but I couldnt find an answer.
I combined autocomplete with goole maps and if a user wants, he/she can move the marker as well and I get address from it. You can find the code below.
When a user searches for instance Nice, France, is it possible to fit Nice from e.g borders to my map? Maybe I have to change the zoom dynamically or I need to set new viewport, I am not sure. So far what I found is, I can give a distance and create a circle to fit that circle to the viewport. But circle's radius is set, so it can fit to Nice but can not fit to Miami.
Hope I could explain what I mean. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#map_canvas {
width: 980px;
height: 500px;
}
#current {
padding-top: 5px;
}
</style>
</head>
<body>
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section>
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area">
</div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {data_arr.push(data_route["long_name"]);}
if (data_administrative_4 !== undefined) {data_arr.push(data_administrative_4["long_name"]);}
if (data_administrative_3 !== undefined) {data_arr.push(data_administrative_3["long_name"]);}
if (data_administrative_2 !== undefined) {data_arr.push(data_administrative_2["long_name"]);}
if (data_administrative_1 !== undefined) {data_arr.push(data_administrative_1["long_name"]);}
if (data_country !== undefined) {data_arr.push(data_country["long_name"]);}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_API_KEY&callback=initMap"></script>
</body>
</html>
The Autocomplete service returns the geometry of the location selected, zoom the map to show those bounds (in the fiddle/snippet I added a rectangle to show the bounds returned, if you don't want that displayed, remove it):
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
}
proof of concept fiddle
html,
body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
#map_canvas {
width: 100%;
height: 80%;
}
#current {
padding-top: 5px;
}
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section style="width: 100%; height:100%;">
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area"></div>
<script>
var rect;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.viewport
})
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.bounds
})
}
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function(evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
var latlngStr = input.split(',', 2);
var latlng = {
lat: parseFloat(latlngStr[0]),
lng: parseFloat(latlngStr[1])
};
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {
data_arr.push(data_route["long_name"]);
}
if (data_administrative_4 !== undefined) {
data_arr.push(data_administrative_4["long_name"]);
}
if (data_administrative_3 !== undefined) {
data_arr.push(data_administrative_3["long_name"]);
}
if (data_administrative_2 !== undefined) {
data_arr.push(data_administrative_2["long_name"]);
}
if (data_administrative_1 !== undefined) {
data_arr.push(data_administrative_1["long_name"]);
}
if (data_country !== undefined) {
data_arr.push(data_country["long_name"]);
}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
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 ?
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);
});
});
I currently have a map that displays a marker on the users geolocation. I have a text input field set to Places Auto-complete. When a user searches a city name, a new marker is placed on the location. However, the old gelocation marker remains. I want to delete the old marker or move it so only 1 marker is on the map. How can I do this?
Here is my code:
<html>
<head>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable:true
});
}, 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
};
map.setCenter(options.position);
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable:true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input type="text" id="location-text-box">
<div id="map-canvas"></div>
</div>
</body>
</html>
Make your marker global, and either hide it or move it to the new location
working code snippet:
var map;
var marker;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true
});
}, 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
};
map.setCenter(options.position);
marker = new google.maps.Marker({
position: options.position,
map: map,
draggable: true
});
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */
(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<div style="height:100%; width:100%">
<input type="text" id="location-text-box" />
<div id="map-canvas"></div>
</div>
File javascript.js
function initialize() {
var mapOptions, map, marker, searchBox, city,
infoWindow = '',
addressEl = document.querySelector( '#map-search' ),
latEl = document.querySelector( '.latitude' ),
longEl = document.querySelector( '.longitude' ),
element = document.getElementById( 'map-canvas' );
city = document.querySelector( '.reg-input-city' );
mapOptions = {
// How far the maps zooms in.
zoom: 8,
// Current Lat and Long position of the pin/
center: new google.maps.LatLng( 23.0224, 72.5751 ),
// center : {
// lat: -34.397,
// lng: 150.644
// },
disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
scrollWheel: true, // If set to false disables the scrolling on the map.
draggable: true, // If set to false , you cannot move the map around.
// mapTypeId: google.maps.MapTypeId.HYBRID, // If set to HYBRID its between sat and ROADMAP, Can be set to SATELLITE as well.
// maxZoom: 11, // Wont allow you to zoom more than this
// minZoom: 9 // Wont allow you to go more up.
};
/**
* Creates the map using google function google.maps.Map() by passing the id of canvas and
* mapOptions object that we just created above as its parameters.
*
*/
// Create an object map with the constructor function Map()
map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.
/**
* Creates the marker on the map
*
*/
marker = new google.maps.Marker({
position: mapOptions.center,
map: map,
draggable: true
});
/**
* Creates a search box
*/
searchBox = new google.maps.places.SearchBox( addressEl );
/**
* When the place is changed on search box, it takes the marker to the searched location.
*/
google.maps.event.addListener( searchBox, 'places_changed', function () {
var places = searchBox.getPlaces(),
bounds = new google.maps.LatLngBounds(),
i, place, lat, long, resultArray,
addresss = places[0].formatted_address;
for( i = 0; place = places[i]; i++ ) {
bounds.extend( place.geometry.location );
marker.setPosition( place.geometry.location ); // Set marker position new.
}
map.fitBounds( bounds ); // Fit to the bound
map.setZoom( 15 ); // This function sets the zoom to 15, meaning zooms to level 15.
// console.log( map.getZoom() );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
latEl.value = lat;
longEl.value = long;
resultArray = places[0].address_components;
// Get the city and set the city input value to the one selected
for( var i = 0; i < resultArray.length; i++ ) {
if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
citi = resultArray[ i ].long_name;
city.value = citi;
}
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: addresss
});
infoWindow.open( map, marker );
} );
/**
* Finds the new position of the marker when the marker is dragged.
*/
google.maps.event.addListener( marker, "dragend", function ( event ) {
var lat, long, address, resultArray, citi;
console.log( 'i am dragged' );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { latLng: marker.getPosition() }, function ( result, status ) {
if ( 'OK' === status ) { // This line can also be written like if ( status == google.maps.GeocoderStatus.OK ) {
address = result[0].formatted_address;
resultArray = result[0].address_components;
// Get the city and set the city input value to the one selected
for( var i = 0; i < resultArray.length; i++ ) {
if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
citi = resultArray[ i ].long_name;
console.log( citi );
city.value = citi;
}
}
addressEl.value = address;
latEl.value = lat;
longEl.value = long;
} else {
console.log( 'Geocode was not successful for the following reason: ' + status );
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: address
});
infoWindow.open( map, marker );
} );
});}